为什么要使用新的Array(3)==“ ,, ;;返回true

问题描述 投票:0回答:2

我发现了一个奇怪的问题:new Array(3) == ',,';//true,但我不知道为什么。

我已经知道在函数Array中传递的数字意味着创建一个新的特定长度的空数组,我不知道',,'是什么意思?我用谷歌搜索,但没有答案。

所以我来堆栈溢出,有人可能会帮助我,我想

javascript arrays
2个回答
1
投票

这是因为当您与loose相等运算符进行比较时,会在数组实例上调用toString()方法。

通过调用==,将左侧的操作数强制变为toString()运算符右侧的类型。

toString()内部调用Array实例上的Array.prototype.join(),由于您的数组中只有孔,因此输出为两个逗号作为字符串:

//Outputs ,, to the console
console.log(new Array(3).toString()); 

//The toString() is calling join()
console.log(new Array(3).join() === new Array(3).toString());

如果对严格相等运算符进行相同操作,则不会发生这种情况,因为类型强制不会发生:

//coercison is happening due to the loose equlity operator
console.log(new Array(3) == ',,')  
 //strict equality does not call toString() on the Array as no type coercion happens
console.log(new Array(3) === ',,')

我之前提到的toString()称为Array.prototype.join(),因此这就是为什么将,,作为Array.prototype.toString()的输出的原因。在不带任何参数的情况下调用join()时,将使用默认的分隔符,连接数组的元素。如果数组为空,它将使用,

连接孔

//This will also be true
console.log([1, 2, 3] == '1,2,3')

//toString() converts array to a string by joing with the default separator internally calling join()
console.log([1, 2, 3].toString() === '1,2,3')

//join() converts array to a string by joing with the default separator
console.log([1, 2, 3].join() === '1,2,3')

0
投票

由于您正在使用==运算符,并且正在将数组与字符串进行比较,真正发生的是使用new Array(3).toString()将数组转换为字符串,并且该数组等于',,'

使用===将导致错误的结果。

© www.soinside.com 2019 - 2024. All rights reserved.