Best Way to Loop Through an Array in JavaScript

深入理解JavaScript中数组遍历方式:标准for循环与for-in循环的区别
本文探讨了在JavaScript中遍历数组时使用标准for循环与for-in循环之间的区别,特别是对于数组作为对象的情况,强调了正确使用标准for循环的重要性,并提供了一种优化方法来避免每次计算数组长度。

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:

1
2
3
4
5
6
7
8
9
var myArray = ["aa", "bb"];

// Object() augmented
Object.prototype.newMethod = "cc";

// for-in loop
for (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:

1
2
3
4
5
6
7
8
9
10
var myArray = ["aa", "bb"];

// Object() augmented

Object.prototype.newMethod = "cc";

//for loop
for (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.

1
2
3
4
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:

1
2
3
4
5
6
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.


In Elasticsearch 7.7, the recommended way to query from multiple indexes using the Transport Java API is to use the MultiSearchRequest API. Here's an example code snippet for querying from multiple indexes using the MultiSearchRequest API: ``` // Create a client object TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300)); // Create a MultiSearchRequest object MultiSearchRequest multiSearchRequest = new MultiSearchRequest(); // Add multiple search requests to the MultiSearchRequest object multiSearchRequest.add(SearchRequestBuilders.searchRequest("index1").source(query)); multiSearchRequest.add(SearchRequestBuilders.searchRequest("index2").source(query)); // Execute the MultiSearchRequest MultiSearchResponse multiSearchResponse = client.multiSearch(multiSearchRequest).actionGet(); // Process the response for (MultiSearchResponse.Item item : multiSearchResponse.getResponses()) { SearchResponse searchResponse = item.getResponse(); // Process the search response for each index } // Close the client object client.close(); ``` In this code snippet, we first create a TransportClient object and a MultiSearchRequest object. We then add multiple SearchRequest objects to the MultiSearchRequest object, with each SearchRequest targeting a different index. We then execute the MultiSearchRequest using the client object, and process the response for each index. Note that the above code snippet uses the deprecated TransportClient API. It is recommended to use the Java High Level REST Client or the Java Low Level REST Client instead.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值