Michael.Lumley
Michael.Lumley

Reputation: 2385

Array.length longer than array

I am getting some strange behaviour out of JavaScript array.length. In particular, I have an array that returns length as 3, when there is only one element in the array, at index 0. I've read this question/answer dealing with incorrect values returned by array.length, but it doesn't answer my question because my array doesn't seem to be associative.

Here's a screenshot of my console, demonstrating the odd behaviour.

Screenshot Odd Array Behaviour

The code is throwing an error because I'm looping over the first array using array.length and the code is trying to acccess the second and third elements it thinks should be in the array, and not finding them. Other entries in the database seem to not have this problem (see the second array in the screenshot).

So here's the question: Why is array.length in the first array 3 instead of 1?

Upvotes: 2

Views: 2132

Answers (1)

Eineki
Eineki

Reputation: 14909

The length Array property in javascript is writable from anyone and is not a reliable source to find the number of elements in the array.

Usually, it is safe to assume that the array has length elements in it, but sometime you can have different behaviours. This one is one of them.

var x = [1,2,3];
x.length = 5;

using a for construct will lead to some undefined values

for (var i = 0; i < x.length; i++) {
    alert(x[i]);
}

using the forEach Array method would result (on Firefox at least) in the desired behaviour.

x.forEach(function(item) {
    alert(item);
});

Note that, if you change the array length to a lesser value than the real value, the array would lose the extra elements and if you restore the original value the extra elements will be lost forever.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

Upvotes: 4

Related Questions