user1675891
user1675891

Reputation:

Getting indexes instead of actual values when looping through an array

I'm using this code.

var stuff = "mango,tango,snake";
for (thing in stuff.split(","))
  console.log(thing);

I was expecting three lines with the words. I'm getting three lines with indexes. I've checked the toString etc. methods. None helped.

  1. Why?
  2. What should I use instead?

Upvotes: 0

Views: 41

Answers (4)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

What should I use instead?

You could use ECMAScript 5 's feature Array.forEach to achieve your need.

var stuff = "mango,tango,snake";
stuff.split(",").forEach(function(thing){ alert(thing); });

Upvotes: 0

Christophe
Christophe

Reputation: 28114

The standard way to loop through an array is to use:

var stuffArray=stuff.split(",");
for (var i=0, stuffLength=stuffArray.length;i<stuffLength;i++) {
    // here you can retrieve the value stuffArray[i]
}

There's also a forEach method, but not supported by older browsers (like IE 8).

A for...in loop loops through the properties of the array object and might give you more than just the array items.

Upvotes: 0

jAndy
jAndy

Reputation: 235962

A Javascript Array is also just an Object and it also inherits from Object. But that Array also inherits from Array.prototype and gets some special methods and behaviors.

But afterall, its just an Object, which means its structure looks like

{
    0:   'mango',
    1:   'tango',
    2:   'snake'
}

If you loop now with for..in over that object, we just get the results you described (and which we should expect). The Keys of the object, are just the index values and we are just looping over the object keys, right?

To get the actual value behind a key, we access the whole object like

objectName[ key ]

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

That's the normal behavior. To log values, use

var arr = stuff.split(",");
for (var thing in arr)
  console.log(arr[thing]);

See the MDN on for in (emphasis mine) :

A different property name is assigned to variable on each iteration.

Upvotes: 1

Related Questions