John Stimac
John Stimac

Reputation: 5493

Javascript for-in statement

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?

Upvotes: 0

Views: 311

Answers (3)

nnnnnn
nnnnnn

Reputation: 150030

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.

Upvotes: 1

peller
peller

Reputation: 4543

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

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

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.

Upvotes: 2

Related Questions