为什么当一个数组与其对应的字符串比较时,它的计算结果为 true?
var a = [1,2,3];
var b = '1,2,3';
console.log(a==b);// true
变量a
存储为其分配的数组的内存地址。那么内存地址如何等于该数组对应的字符串。
最佳答案
这是由于语言的规范和语义造成的。该数组是一个对象,在与字符串比较之前将被强制转换为字符串。
您可以遵循转换路径:
7.2.15 Abstract Equality Comparison
- If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return the result of the comparison ? ToPrimitive(x) == y.
它基本上会经历所有步骤,直到到达11。。
ToPrimitive(Array)
最终引用并调用属性 .toString
https://tc39.es/ecma262/#sec-array.prototype.tostring
https://tc39.es/ecma262/#sec-object.prototype.tostring
关于javascript - 为什么数组等于其对应的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62207802/