Best Way to Loop Through an Array in JavaScript

来源:互联网 发布:淘宝店的站内推广 编辑:程序博客网 时间:2024/05/16 07:54

http://www.sebarmeli.com/blog/2010/12/06/best-way-to-loop-through-an-array-in-javascript/

Last week, a colleague of mine asked me “Why are you using a ‘standard for loop’ rather than the faster ‘for-in loop’ to loop through an Array in JavaScript?” and for this reason I’m going to write a short explanation about that.

First of all, when I talk about the standard ”FOR loop”, I mean something like

1
for (var i=0; i < myArray.length; i++){}

instead the ”FOR-IN loop” is something like:

1
for (var i in myArray){}

for-in loop is faster…just to type, for a lazy developer :) and it’s a common mistake especially for developers coming from Java programming (I’m a Java developer as well, that’s why I know that :P), trying to port Java into JavaScript.

The two main problems with for-in loop are : 1) It enumerates through all the properties even the ones associated to the Object (that can be augmented previously) 2) The order of the elements is not guaranteed.

You may not interested in the order of the elements(even if often you are), but you need to deal with the first issue and that’s what can happen:

123456789
var myArray = ["aa", "bb"];// Object() augmentedObject.prototype.newMethod = "cc";// for-in loopfor (var i in myArray) {  console.log(myArray[i]); //"aa", bb", "cc"}

The console will print not only the two elements from the array, but also the value of the new property in the Object. Remember that array are objects in JavaScript, at the root of the prototypal chain there is always Object and you never know if Object has augmented previously by a library or some script.

The correct way to execute that loop is using the for loop:

12345678910
var myArray = ["aa", "bb"];// Object() augmentedObject.prototype.newMethod = "cc";//for loopfor (var i=0; i < myArray.length; i++) {  console.log(myArray[i]); //"aa", "bb"}

Actually, we can make a micro-optimization to this, “caching” the length of the array and avoiding every time to calculate the length of the array.

1234
var myArray = ["aa", "bb"];for (var i=0,  tot=myArray.length; i < tot; i++) {  console.log(myArray[i]); //"aa", "bb"}

Notice that there is a comma between “var i=0” and “tot=myArray.length” as the “for loop” accepts three expressions.

If you find this last way a bit weird, you could do something like:

123456
var myArray = ["aa", "bb"],  i=0;for (tot=myArray.length; i &lt; tot; i++) {  console.log(myArray[i]); //"aa", "bb"}

So it’s strongly recommended to use the FOR LOOP to loop through an Array and remember that Java and JavaScript are different.

In the next post, I may go through where the “for-in” loop is used.


0 0
原创粉丝点击