Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

Should negative indexes in JavaScript arrays contribute to array length?

In javascript I define an array like this

var arr = [1,2,3];

also I can do

arr[-1] = 4;

Now if I do

arr = undefined;

I also lose the reference to the value at arr[-1].

SO for me logically it seems like arr[-1] is also a part of arr.

But when I do following (without setting arr to undefined)

arr.length;

It returns 3 not 4;

So my point is if the arrays can be used with negative indexes, these negative indexes should also be a part of their length**. I don't know may be I am wrong or I may be missing some concept about arrays.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

SO for me logically it seems like arr[-1] is also a part of arr.

Yes it is, but not in the way you think it is.

You can assign arbitrary properties to an array (just like any other Object in JavaScript), which is what you're doing when you "index" the array at -1 and assign a value. Since this is not a member of the array and just an arbitrary property, you should not expect length to consider that property.

In other words, the following code does the same thing:

?var arr = [1, 2, 3];

?arr.cookies = 4;

alert(arr.length) // 3;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...