为什么“ ,,”= = Array (4)在 Javascript 中?

启动解释器/控制台并尝试进行比较

> ",,," == Array(4)
True

为什么?一开始我想,也许因为您可以将“ ,,”想象成一个包含4个字符的数组,其中有一个’0’结束切片,这可能就是原因,但是

> "..." == Array(4)

Returns "False". So... why? I know it's some idiosyncratic bit of duck typing in Javascript, but just curious what underlines this behavior. Gleaned this from Zed Shaw's excellent 顺便说一下.

7435 次浏览

因为右边的操作数被转换为字符串,而 Array(4)的字符串表示形式是 ,,,:

> Array(4).toString()
",,,"

如果使用数组构造函数并传递一个数字,它会将数组的长度设置为该数字。所以你可以说你有四个空索引(和 [,,,]一样) ,数组的默认字符串表示是一个逗号分隔的元素列表:

> ['a','b','c'].toString()
"a,b,c"

比较的工作原理在 规范的11.9.3节中有描述,在那里你会看到(x == y) :

如果 Type (x)是 String 或 Number,Type (y)是 Object,
return the result of the comparison X == 太原始了().

(数组是 JavaScript 中的对象)

and if you follow the ToPrimitive method you will eventually find that it it calls toString.

尝试使用 ===。当在 Javascript 中使用 ==时,它会尝试强制转换变量,从而导致类似这样的问题。控制台将 Array(4)强制转换为字符串表示(即 Array(4).toString) ,即 ",,,"。逗号之所以存在,是因为 .toString()函数将它们添加到数组中的单独项。

请看下面的片段:

document.write( Array(4).toString() );

内部正在运行

",,," == Array(4).toString()

将 Array 与字符串进行比较之前,将强制将 Array 与字符串进行比较。将一个空的4元素 Array 强制转换为一个字符串将生成该确切的字符串。

这是因为 Array(4)初始化一个包含4个空值的数组,一个 ==隐式转换,所以:

 ",,," == Array(4)


",,," == Array(4).toString()


",,," == ["", "", "", ""] // note 3 commas for 4 values


",,," == ["", "", "", ""].toString()

Are all similar.

== does implicit type conversions before comparing the values, which can result in unpredictable results. Use === to check the type and the value.

我一开始以为是原型机的问题,但经过一番调查后,我得出了一个可悲的结论。

显然,这是一个内部和更模糊的 Js 的东西,没有太多的逻辑..。

试试看

Array(4)==Array(4)

也没有强迫类型。

Array(4)===Array(4)

你会得到假的

你知道,null==nullnull===null,甚至 undefined==undefinedundefined===undefined返回真... 所以... 这有点模糊..。

Array(4)==[,,,] should be true also