Reputation: 634
How can I get the highest key in an array like that:
foo[0] == undefined
foo[1] == "bar"
foo[2] == undefined
foo[3] == undefined
foo[4] == "bar"
foo.length
returns me 2, so if i iterate foo.length
times, I'll never get the last value.
Or is there a way to count an array considering the undefined values as well?
Upvotes: 2
Views: 3559
Reputation: 5612
I am unsure why your code is not working, .length
on an array like that shows 5 correctly in my example here
However, if you do not set values at all on specific indexes, you can do this :
var foo = [];
foo[1] = "bar";
foo[4] = "bar";
//grab existing indexes that have values assigned
var indexes = foo.map(function(val, idx) { return idx; });
//get the last one, this + 1 is your real length
var realLength = indexes[indexes.length - 1] + 1;
console.log("Real length: ", realLength);
//iterate using for loop
for(var i=0; i<realLength; i++) {
var val = foo[i];
console.log(i, val);
}
Upvotes: 3