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

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

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

  • !!双重非运算符是显式地将任意值强制转换为其对应的布尔值。
    同样的转换可以通过 [Boolean]函数完成。

  • ②不要用创建 Boolean 对象的方式将一个非布尔值转化成布尔值,直接将 Boolean 当做转换函数来使用即可,或者使用[双重非(!!)运算符]:

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容