2012-12-17 100 views
1

有人能解释这里发生了什么吗?我试图使用javascript !!(双重)运算符as described hereHTML5 local storage(我存储0和1值和测试的真实性,但我也需要一个失踪的关键是假的,因此未定义在。开始布尔运算符在if语句不起作用

虽然类型转换时,回声控制台为假,它不会在 '如果' 语句

var foo = undefined; 

// outputs undefined 
console.log(foo) 

// typecast to non-inverted boolean 
console.log(!!foo); 

if (!!foo) { 
    console.log("If was false before, why won't this execute?"); 
}​ else { 
    console.log("It didn't work"); 
}​​​​​​​​​​​​​​​ 

生产:

undefined 
false 
It didn't work 

http://jsfiddle.net/YAAA7/
(铬v 23.0.1271.97 &火狐16.0.1,Mac OS X 10.8.2)

编辑 - 纠正代码:

(以前的 '如果' 语句只是评估为假的,从而使分支将永远不会运行。)

var foo = false; 

// outputs undefined 
console.log(foo) 

// typecast to non-inverted boolean 
console.log(!!foo); 

if (!!foo == false) { 
    console.log("Matches for foo undefined, foo = 0 and foo = false"); 
} else { 
    console.log("Matches for foo = 1 and foo = true"); 
}​ 

http://jsfiddle.net/YAAA7/1/

+1

好,'!! foo'是'FALSE',就像你说的,所以'else'分支将被采用。这是它应该如何工作的。 –

+0

在答案的评论之一,有人指出,'!!'不是运营商 - 这是两个'!'运营商。 – AlexMA

+0

这是对变量的值进行反义的反义词。 –

回答

1
var foo = undefined; 

foo将返回true。因为在JavaScript中,未定义的,0,NaN,false和null都被认为是falsey值。

http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN

从代码:

var foo = undefined; //false 

console.log(!!foo); // !!foo = false; 

if(!!foo) { //false 
    console.log("It will not come because the condition fails"); 
}else{ 
    console.log("Else Part"); 
} 
4

这是预期的行为。如果你加倍不假,你就会失败。这个,! l是不是运营商。这个,!!,是两个不是运营商。 double not运算符有时用于转换为布尔类型。

! false === true 
!! false === false