Reputation: 8398
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
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
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
Reputation: 4842
Instead of:
for ( i in ocenia)
{
console.log(i)
}
do
for ( i in ocenia)
{
console.log(ocenia[i])
}
Upvotes: 0
Reputation: 6771
You have to do:
for ( i in ocenia)
{
console.log(ocenia[i]);
}
which means to get the i
th 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