“==”判定較為輕松,只需值相等,可以進(jìn)行類型轉(zhuǎn)換;
“===”判定嚴(yán)格,類型與值都必須相等;
console.log(3 == "3"); // true
console.log(3 === "3"); // false.
console.log(true == '1'); // true
console.log(true === '1'); // false
console.log(undefined == null); // true
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.
特殊的
console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false
[字符串文字與字符串對象是不同的]
console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false
要查看嚴(yán)格相等為什么返回false的原因,請看以下內(nèi)容:
console.log(typeof "This is a string."); // string
console.log(typeof new String("This is a string.")); //object
一些Tips
①?。?/strong>雙重非運算符是顯式地將任意值強(qiáng)制轉(zhuǎn)換為其對應(yīng)的布爾值。
同樣的轉(zhuǎn)換可以通過 [Boolean]函數(shù)完成。②不要用創(chuàng)建
Boolean對象的方式將一個非布爾值轉(zhuǎn)化成布爾值,直接將Boolean當(dāng)做轉(zhuǎn)換函數(shù)來使用即可,或者使用[雙重非(!!)運算符]:
var x = Boolean(expression); // 推薦
var x = !!(expression); // 推薦
var x = new Boolean(expression); // 不太好
對于任何對象,即使是值為 false 的 Boolean 對象,當(dāng)將其傳給 Boolean 函數(shù)時,生成的 Boolean 對象的值都是 true。
var myFalse = new Boolean(false); // false
var g = new Boolean(myFalse); // true
var myString = new String("Hello");
var s = new Boolean(myString); // true