JS中“==”与“===”的区别,

2019-12-08  本文已影响0人  仙姑本姑

“==”判定较为轻松,只需值相等,可以进行类型转换;
“===”判定严格,类型与值都必须相等;

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

要查看严格相等为什么返回false的原因,请看以下内容:

console.log(typeof "This is a string."); // string
console.log(typeof new String("This is a string.")); //object

一些Tips

var x = Boolean(expression);     // 推荐
var x = !!(expression);          // 推荐
var x = new Boolean(expression); // 不太好

对于任何对象,即使是值为 false 的 Boolean 对象,当将其传给 Boolean 函数时,生成的 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
上一篇下一篇

猜你喜欢

热点阅读