操作符和事件中的javascript

操作符和事件中的javascript,javascript,Javascript,更新: 为什么前者返回true,而其余的返回false?可能仅仅是窗口对象有一个名为onhashchange的属性,但该属性的值当前为null,因此被认为是false 'onhashchange' in window; //returns true window['onhashchange']; //returns false window.onhashchange; //returns false; …其中是一个双重否定,是一个将值转换为真/假的技巧。我认为在第一个操作的帮助下,您只需检

更新:
为什么前者返回true,而其余的返回false?

可能仅仅是
窗口
对象有一个名为
onhashchange
的属性,但该属性的值当前为
null
,因此被认为是false

'onhashchange' in window;  //returns true
window['onhashchange']; //returns false
window.onhashchange;  //returns false;

…其中
是一个双重否定,是一个将值转换为真/假的技巧。

我认为在第一个操作的帮助下,您只需检查window对象中是否存在这样的事件,就可以返回true。另外两个函数告诉您是否实现了这样的处理程序,并且还没有实现,您将得到false。 你能检查一下吗

var a = { 'foo': null }
console.log('foo' in a) // true
console.log(a.foo) // null
console.log(!!a.foo) // false
是的,不管怎样,它现在将返回true,因为我们已经定义了那个变量。。。所以很可能

window.onhashchange = function() {}
window['onhashchange'];
只需检查浏览器是否支持它

'onhashchange' in window;
只需检查处理程序是否已经实现

另外,你也可以对此感兴趣,这里@Andy E写道:

在使用它检查事件支持时,您应该谨慎行事。除Mozilla之外的所有实现都支持元素中的“eventname”作为DOM事件的测试,Firefox将在此处导致false,除非定义了处理程序

更新:要查看“窗口中的x”和“窗口.x”(等于窗口['x'])之间的区别,请查看以下脚本及其输出:

window['onhashchange']; //returns false
window.onhashchange;  //returns false;

UPDATE2:-本文介绍了如何跨浏览器进行事件检测(因为“窗口中的事件”在Mozilla中不起作用;本文还回答了为什么会这样)

onhashchange是非标准的(据我所知),因此不完全受支持。我想它要么是被淘汰了要么是一些奇怪的事情。尝试设置间隔循环。现在,您显然是一位使用window['onhashchange']的经验丰富的JavaScript开发人员,但坦率地说,我自己从未听说过。在不讨论浏览器问题的情况下,但从纯JavaScript的角度来看,window中的x与window[x],window.x有什么不同?window中的x检查是否存在这样一个属性的方式,“window[x]/window.x“如果存在该属性,则返回该属性的值。我将用例子来回答更新
window['onhashchange']; //returns false
window.onhashchange;  //returns false;
var foo = {};
console.info( 'bar' in foo ); // false, because no such proeprty
console.info( foo.bar ); // undefined, because no such property
console.info( foo.bar ? 'true' : 'false' ); // 'false' because no such property

foo = { bar: false };
console.info( 'bar' in foo ); // true, because there is such property
console.info( foo.bar ); // false, because this is value of bar property
console.info( foo.bar ? 'true' : 'false' ); // 'false' because foo.bar is false

foo = { bar: 1 }; 
console.info( 'bar' in foo ); // true, because there is such a property
console.info( foo.bar ); // 1, because this is value of bar proeprty
console.info( foo.bar ? 'true' : 'false' ); // 'true', because foo.bar is 1 (which is not 0 which meant to be false)

foo = { bar: 0 }; 
console.info( 'bar' in foo ); // true, because there is such a property
console.info( foo.bar ); // 0, because this is value of bar proeprty
console.info( foo.bar ? 'true' : 'false' ); // 'false', because foo.bar is 0 (which meant to be false)