如何解释下面的现象?
var a1 = 'a';
var a2 = new String('a');
var a3 = new String('a');
a1 == a2; // true
a1 == a3; // true
a2 == a3; // false
a1 === a2; // false
a1 === a3; // false
a2 === a3; // false
[]==[] // false
[]===[] // false
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
补充:
首先
a2和a3的类型是对象。此处
a2、a3==a1的时候不同数据类型比较是调用了valueOf方法的,所以true。而
===的时候不会转换数据类型,所以是false.a2===a3,因为对象的内存地址不同,所以是false然后
[]也是引用数据类型,也是比较地址。所以==和===都是false补充:
基本数据类型和Object类型(Date除外)的
==比较。会首先调用
valueOf方法,若返回值非基本数据类型,会再调用toString方法,返回值若类型不同还会调用Number转换为数字。1.a1==a2 a2为对象,==比较时转字符串所以为true,===时不转为false;
2.a1==a3 同1
3.a2 == a3 new String()返回对象,对象==,===判断比较地址,地址相同为true,否则为false。a2和a3虽然值相同,但是地址是不同的。
4.a1 === a2 见1
5.a1 === a3 见1
5.a2 === a3 见3
6.[]==[]/[]===[] []是一个数组,同对象比较,都是比较地址。
请参考MDN
The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
The identity operator returns true if the operands are strictly equal (see above) with no type conversion.
区别是==在左右2数,数据类型不等的情况下进行类型转换再比较,一般是右边转成左边的数据类型再做比较。而===不做类型转换直接比
内存地址不同
造成的false