8

I found this code:

if (!("aa" in window)) {  
    alert('oh my god');
    var aa = 1;  
}  
alert("aa" in window);
alert(aa);

This code the second alert is alert true,but,the third alert is 'undefined',and the alert in the 'if' is not run. Why?

I think the reason is the in; what is its effect?

I searched on Google, but found nothing, because Google thinks the word ‘in&srquo; is a filter word.

We always use the in in loops, but, frankly speaking, I use it but don’t really understand it.

4

3 回答 3

16

This tests if the window object has a property (filled or not) whose key is "aa".

This operator is very useful because it works even if the value is undefined :

window.aa = undefined; // or just aa=undefined if you're in the global scope
console.log('aa' in window); // logs true

It also works if the property isn't enumerable :

console.log('length' in []); // logs true

In your case, there may not be an aa value, but if the alert shows you true, the property was added to window.

MDN reference on in

Note that the for...in statement is different in that it doesn't really use the in operator but is a specific construct.

MDN reference on for...in


EDIT : an explanation of your edited question (very different from the first one) :

Your confusion seems to arise from the fact you declared the var aa = 1; in a block. You should know that the scope of a variable in JavaScript is either a function of the global scope and that declarations are hoisted. So your code is in fact equivalent to

var aa = undefined;
if (!("aa" in window)) { // aa is in window, so we don't enter here
    alert('oh my god');
    aa = 1;  
}  
alert("aa" in window); // yes, the property exists, it's true
alert(aa); // aa is still undefined
于 2013-05-30T08:57:10.673 回答
2

按顺序处理警报:

  • 警报 #1永远不会到达,因为("aa" in window) === true布尔if条件为假。

JavaScript 有函数作用域,变量aa首先被“提升”到作用域的顶部,所以它定义了。

  • 警报 #2

"aa" in window为真,因为该变量在提升时已添加到窗口对象。相当于只写:

var foo;
"foo" in window (which === true)
  • 警报 #3

来自标准 ECMA-262 ECMAScript 语言规范

变量语句声明按照 10.5 中定义创建的变量。变量在创建时初始化为未定义。具有 Initialiser的变量在执行 VariableStatement 时分配其AssignmentExpression的值,而不是在创建变量时。

aa由于从未执行分配,因此未定义。

于 2013-05-30T10:39:51.153 回答
1

in检查属性是否存在于Object

// in the below snippet they are checking if 'aa' property exists in 'window' Object . Since variables are function declarations are hoisted. you'll never enter inside if block .

var aa = undefined ;
if (!("aa" in window)) {   //2 => 'aa' property exists 
    alert('oh my god');  
    aa = 1;         // 1 =>  hoisted 
}  
于 2020-04-17T07:54:39.540 回答