0

Here is my object ,

ocenia=["-23.725012", "-11.350797", "-45.460131"]

I want to print elements of object ocenia.

What i am trying to do is ,

for ( i in ocenia)
   {
      console.log(i)
   }

It is just printing indexes of elements like ,

0 
1 
2

Whats wrong i am doing here ?

Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
  • 1
    [Why for in loops for arrays are bad](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – Andy Mar 28 '14 at 11:06
  • 2
    Note that `ocenia` is not an object, but an array – neelsg Mar 28 '14 at 11:07

5 Answers5

4

Please please please don't iterate over JS Arrays with for..in. It's slow and tend to cause strange bugs when someone decides to augment Array.prototype. Just use old plain for:

for (var i = 0, l = ocenia.length; i < l; i++) {
  console.log(ocenia[i]);
}

... or, if you're among the happy guys who don't have to worry about IE8-, more concise Array.prototype.forEach():

ocenia.forEach(function(el) {
  console.log(el);
});
raina77ow
  • 103,633
  • 15
  • 192
  • 229
1

Try this

   for ( i in ocenia)
   {
      console.log(ocenia[i])
   }

for array you should use for (;;) loop

for(var i=0, len = ocenia.length; i < len; i++){
       console.log(ocenia[i]);
}

OR forEach (recommended )

ocenia.forEach(function(item, index){
   console.log(item)
});
Anoop
  • 23,044
  • 10
  • 62
  • 76
1

You have to do:

for ( i in ocenia)
{
    console.log(ocenia[i]);
}

which means to get the ith element of ocenia.

P.S. it's an array, not object. And never iterate over arrays with for..in. Further reading.

Use this for the best practice:

for (var i = 0, len = ocenia.length; i < len; i++)
{
    console.log(ocenia[i]);
}
Community
  • 1
  • 1
Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
1

Just try the following code

console.log(oceania[i])
MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65
0

Instead of:

for ( i in ocenia)
   {
      console.log(i)
   }

do

for ( i in ocenia)
   {
      console.log(ocenia[i])
   }
neelsg
  • 4,802
  • 5
  • 34
  • 58