Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8398

Print values from javascript object

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 ?

Upvotes: 0

Views: 71

Answers (5)

Anoop
Anoop

Reputation: 23208

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

Upvotes: 1

raina77ow
raina77ow

Reputation: 106463

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

Upvotes: 4

neelsg
neelsg

Reputation: 4842

Instead of:

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

do

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

Upvotes: 0

MusicLovingIndianGirl
MusicLovingIndianGirl

Reputation: 5947

Just try the following code

console.log(oceania[i])

Upvotes: 1

Gaurang Tandon
Gaurang Tandon

Reputation: 6771

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

Upvotes: 1

Related Questions