Why does “,,,” == Array(4) in Javascript?

后端 未结 6 2171
暖寄归人
暖寄归人 2020-12-12 23:14

Boot up your interpreter/console and try the comparison

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

Why? At first I thought maybe since you could think

6条回答
  •  旧时难觅i
    2020-12-12 23:37

    Try using ===. When using == in Javascript, it will attempt to cast the variables, thus leading to issues like this one. The console is casting Array(4) to the string representation (i.e. Array(4).toString), which is ",,,". The reason the commas are there is that the .toString() function adds them to separate items in an array.

    See the snippet below:

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

提交回复
热议问题