Last active
August 29, 2015 14:02
-
-
Save youxiachai/2ef78c43a6d6a1993af0 to your computer and use it in GitHub Desktop.
js 真值练习
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log(undefined >= 0); // false | |
console.log(null === 0); // false | |
console.log(null == 0); // false | |
console.log(0 >= 0); // true | |
//坑来了.. 对了js只有恒等 只有 !==, === 可没有恒比较 >== 的写法. | |
// 直觉上 null >= 0 应该跟 null == 0 或者 undefined >= 0 的效果一样的啊..但是事实不是这样的.. | |
console.log(null >= 0); //true | |
//为避免入坑.对于可能有null 值的判断,我可以简单处理 | |
console.log(!!(null && null >= 0)) // false | |
//你以为上面的方式就解决问题了? 图样图森破 | |
console.log(!!(0 && 0 >= 0)) // false | |
// 那办法? | |
// 可以尝试这种, 如果要处理 0 值 | |
var x = 0 // 或者 var x = null; | |
if(x == 0) { | |
if (x > = 0){ | |
console.log('done'); | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log([] == []) // false | |
console.log([] === []) // false | |
console.log([] === ![]) // false | |
console.log(![]) // false | |
console.log([] == ![]) // true ! | |
// 这个应该是 false 吧 | |
console.log({} == {}) // false 对头,学得真好 | |
// 这个肯定false 啦 | |
console.log(!{}) // false | |
// | |
//根据以上推论 看到这个例子你会想,,嗯,下面这个肯定是true ! | |
console.log({} == !{}) // false 图样图森破! | |
// 吊毛js 坑真多,为毛会这样啊? 因为对象类型转换调用了,toString().... | |
console.log(![].toString()) // true | |
console.log(!{}.toString()) // false | |
//这么说又不对了!!! 吃我大招.. | |
console.log([].toString() == ![].toString()); // false | |
// | |
//这个才是为师([] == ![])的完全状态 | |
console.log([].toString() == !new Boolean([].toString())); // true | |
console.log('' == !new Boolean([].toString())); // true | |
//因为 {}.toString() | |
console.log([].toString()) // '' | |
console.log({}.toString()) //[object Object] | |
//那样 完全说得通了... | |
console.log(new Boolean ({}.toString()) == !new Boolean({}.toString())); // false | |
//嗯,这么就完了...!? 根据上面推论 | |
console.log(![].toString()) // true | |
console.log(!{}.toString()) // false | |
//脑海可能是这么想这个等价于console.log(!!'') 于是这个肯定是false 啦... | |
console.log(!![]) //true wtf !!!!!!!!!!!!! | |
//这个肯定是true 啦... | |
console.log(!!{}) //true | |
//为什么 console.log(!![]) -> true ? 其实真相是这样...叫你不认真看boolean 是怎么包的.. | |
console.log(new Boolean([].toString())) // {} | |
console.log(!!new Boolean([].toString())) // true | |
//相当于 | |
console.log(!!{}) // true | |
// 学的不错了吧.. 考验一下你! | |
console.log([] == !{}) | |
console.log({} == ![]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment