最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Why javascript shows 0 length for array with object property instead of indexed element - Stack Overflow

programmeradmin1浏览0评论

For Example:

var arr = [];
arr[3.4] = 1;
console.log(arr.length);

In the above code sample the length property holds zero why and what happened inside JS parser because it's length is zero.

For Example:

var arr = [];
arr[3.4] = 1;
console.log(arr.length);

In the above code sample the length property holds zero why and what happened inside JS parser because it's length is zero.

Share Improve this question asked Jan 8, 2016 at 13:38 gvgvgvijayangvgvgvijayan 2,5061 gold badge24 silver badges37 bronze badges 1
  • Please look into this Length of a JavaScript object – Nikhil Goud Commented Jan 8, 2016 at 13:47
Add a ment  | 

4 Answers 4

Reset to default 10

An array's length is reflective of the largest array index present in the array. An "array index" (see below) is a property name that is an integer value less than 232−1. Since 3.4 is not an integer, setting it does not alter the length.

Arrays are objects, so there is no reason why an array can't have a property named 3.4, but that property doesn't influence the length because its name does not fit the criteria of an array index.

ES2015 9.4.2, Array Exotic Objects defines an "array index" as an integer less than 232−1:

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."

And that definition is used in relation to the length value (emphasis mine):

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 own property whose name is an array index; whenever an own property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever an own property is added whose name is an array index, the value of the length property is changed, if necessary, to be one more than the numeric value of that array index...

A JavaScript array can not have fractional indexes.

What you have done there is assigned a property called "3.4" on the array object.

This does not affect the length property, which is designed to return one number higher than the highest valid index.

If you think about how arrays are supposed to work, you should realise a fractional offset doesn't make sense.

You could try using an object vs an array.

var arr = {};
arr[3.4] = 1;
arr[3.5] = 2;
arr[3.6] = 3;
console.log(Object.keys(arr).length);

You must use an integer as an index, not a float.

var arr = []; arr[3] = 1; console.log(arr.length);

发布评论

评论列表(0)

  1. 暂无评论