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 ?

2
  • 1
    Why for in loops for arrays are bad Commented Mar 28, 2014 at 11:06
  • 2
    Note that ocenia is not an object, but an array Commented Mar 28, 2014 at 11:07

5 Answers 5

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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]);
}

Comments

1

Just try the following code

console.log(oceania[i])

Comments

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)
});

1 Comment

For...in loops for arrays is a bad idea.
0

Instead of:

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

do

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

1 Comment

For...in loops for arrays is a bad idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.