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

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

var arr = [\"He         


        
4条回答
  •  -上瘾入骨i
    2021-01-05 07:52

    javascript length is calculated as 1+(highest numeric index element). so when you add arr['Hello'], you are only adding a string index which is not taken into account when calculating the array length.

    This is the actual definition of the array length property as described in ECMAScript 5.1:

    Every Array object has a length property whose value is always a nonnegative integer less than 232. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

提交回复
热议问题