I'm trying to output the keys of an array in javascript like this:
data=[8, 4, 6, 9, 5, 2, 4, 6];
for(i in data){console.log(i);}
But instead of only outputting the keys, it outputs this:
0
1
2
3
4
5
6
7
$family
each
clean
associate
link
contains
extend
getLast
getRandom
include
combine
erase
empty
flatten
hexToRgb
rgbToHex
min
max
average
sum
unique
shuffle
Why? And how can I make it stop after outputting the array keys?
3 Answers 3
Use a "normal" for loop instead:
for(var i = 0; i < data.length; i++) {
console.log(data[i]);
}
JavaScript's for...in construct iterates over all properties of the object, so you get all of the properties/methods on Array.prototype (in fact, it will go all the way up the prototype chain) as well as the elements you're expecting.
1 Comment
forEach because of the lack of browser support. If you need to support all major browsers, don't even think about reliable native forEach support for a few years yet.This is because Arrays are objects, and for-in iterates properties, not by Array indices. You could do this: data.forEach(function(a,i){console.log(i);}) or you could examine the properties and see if they "in" Array.prototype
Comments
A for..in loop goes through all enumerable properties of an object. I don't know how all those extra properties came to be defined on your array - are you using a library that adds them to Array.prototype?
You should use a traditional for loop to go through an array's numerically indexed items - this will automatically ignore any other properties. If you just want to output the indexes then something like:
for (var i=0; i < data.length; i++) {
if (typeof data[i] !== "undefined")
console.log(i);
}
Note that .length returns one higher than the highest defined index, but that doesn't mean that all lower indexes actually have a value in them so I've included a check that each item is not undefined. You can remove that if undefined is a valid value in your array - in practice I rarely use arrays with "holes" in them, but I mention it for completeness.
P.S. You could use .forEach(), but it isn't supported by older browsers.
5 Comments
delete all elements will have a value - and undefined is a valid value, too. So usually the check for undefined is no really necessaryvar x=[]; x[20]=true; all the elements less than index 20 will not have a value, with no use of delete. But it's rare to code that way and yes, undefined may be a valid value and that's why I noted that that test could be removed if not needed.Array.forEach() you'll see it allows for elements that have been deleted or never set, so obviously some people out there somewhere are using arrays more like objects...somevar[999999] - and of course it's not an object but and array.. and he even loops over this huge array.