Let's say I have
myArray = ['item1', 'item2']
I tried
for (var item in myArray) {console.log(item)}
It prints 0 1
What I wish is to have item1 item2
Is there any other syntax that works without using
for (var i = 0; i < myArray.length; i++)
Join Stack Overflow to learn, share knowledge, and build your career.
|
Let's say I have
I tried
It prints 0 1 What I wish is to have item1 item2 Is there any other syntax that works without using
|
||||
|
You can use
|
|||||||||||||||||
|
|
What you probably want is
Your original loop didn't display the expected results because
1 Unfortunately, someone may have added enumerable properties to the array or its prototype chain which are not numeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from So, this is not (as I'd originally thought) an academic question, i.e.:
According to your comment (emphasis mine):
You have a misguided aversion to Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues. |
|||||||||||||||||||||
|
|
To print 'item1' , 'item2', this code would work.
|
|||
|
|
|
In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use
All array methods which you can use to iterate safely over dense arrays use the See also Are Javascript arrays sparse?. |
||||
|
|
|
Use the built-in Javascript function called map. .map() will do the exact thing you're looking for! |
|||||
|
forloop or the.forEach()function? – Pointy Apr 1 '15 at 18:09for (var propertyName in myArray)would make the issue with the observed behavior more clear. In any case, for a higher-order construct, seeArray.forEachbut note it has a number of implications that make it different from either of the above forms. (The differences between the forms are covered by many duplicates.) – user2864740 Apr 1 '15 at 18:10lengthdoesn't "calculate" the size of the array. The length of an array is an intrinsic value of the Array type. – user2864740 Apr 1 '15 at 18:13lengthwas calculated, you could just cache it:for (var i = 0, length = arr.length; i < length; i++)– Felix Kling Apr 1 '15 at 18:23