Why doesn't the length of the array change when I add a new property?

前端 未结 4 1691
不思量自难忘°
不思量自难忘° 2021-01-05 07:16

var arr = [\"He         


        
4条回答
  •  遥遥无期
    2021-01-05 07:50

    This happens because length is only updated when a new numeric property is added to the array as required by the specification:

    The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.

    And an array index is specified to be:

    A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1.

    However, arrays are also objects - so you can add non-array-index properties to an array, just like you can add properties to any other JavaScript object (which is why your example doesn't throw either).

提交回复
热议问题