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

后端 未结 6 2172
暖寄归人
暖寄归人 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条回答
  •  难免孤独
    2020-12-12 23:40

    Because the right hand operand is converted to a string and the string representation of Array(4) is ,,,:

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

    If you use the array constructor function and pass a number, it sets the length of the array to that number. So you can say you have four empty indexes (same as [,,,]) and the default string representation of arrays is a comma-separated list of its elements:

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

    How the comparison works is described in section 11.9.3 of the specification. There you will see (x == y):

    8. If Type(x) is either String or Number and Type(y) is Object,
    return the result of the comparison x == ToPrimitive(y).

    (arrays are objects in JavaScript)

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

提交回复
热议问题