行则将至

人生在勤,不索何获

0%

JS == 和 === 的区别

区别

在 JS 项目里,除了能看到 == 操作符来判断两个变量是否相等外,我们还会看到 === 操作符,这两者有什么区别?

  • 对于 String, number 这些值类型== 操作符会先把两边的变量进行类型强制转换成相同的类型再比较是否相等=== 操作符则不会进行类型转换,而是直接进行比较。
  • 对于 array, object 这些引用类型===== 是没有区别的,因为它们比较的是 “指针地址 ” 。
  • 值类型和引用类型之间比较,===== 是有区别的;==操作符会先把高级类型转换为基础类型 之后,进行值的比较;=== 操作符则不会进行转换,类型不同,直接返回 false

也就是说,== 操作符只要求比较两个变量的值是否相等=== 操作符则是要求两个变量的值和类型都要相同 ;类似地,!= 操作符会去做类型强制转换,!== 操作符则不会转换类型。

值类型

1
2
3
4
5
6
let a = 1;
let b = '1';

console.log(a == b);
console.log(a === b);

引用类型

1
2
3
4
5
6
7
8
9
10
11
console.log("*********************************");
let a = {val:1};
let b = {val:1};
console.log(a==b);
console.log(a===b);

console.log("*********************************");
c = a;
console.log(a==c);
console.log(a===c);

注意事项

JS == / ===注意事项:

  • 对于特殊值 NaN(Not a Number)表示非数字,NaN 和任何数(包括它自己)做相等比较,都会返回 false,所以判断 NaN 最好用 isNaN() 函数
  • undefined 和 null,两者的值相比较,会返回 true。
    1
    2
    3
    console.log(undefined==null)
    console.log(undefined===null)

  • 由于 == 和!= 操作符带来的类型隐式转换规则非常繁琐,还有为了避免数据类型混淆导致出现 bug,还是推荐使用 === 操作符和!== 操作符。

Stack Overflow 相关

So there you have the two common sources of errors in Javascript comparisons: 1. comparing different types with == can lead to ==unexpected type conversions.== 2. comparing objects and arrays is based on ==references not values stored inside==.

As the existing answer already says, Typescript is designed as a superset of Javascript. So it doesn't change the behaviour of these comparison operators. If you write == in Typescript, you get type conversions.

So how is this fixed? ==With the compiler. ==If you actually do write code that compares incompatible types with == it's a compiler error. Try compiling the following sample:

1
2
3
4
let str = "1";
let num = 1;

console.log(str==num);

参考:

nowjava.com

javascript - Why use triple-equal (===) in TypeScript? - Stack Overflow