JS中“==”與“===”的區(qū)別,

“==”判定較為輕松,只需值相等,可以進(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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容