Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to learn more about for loops in JavaScript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What this article shares to you is about how to deeply understand the for cycle in JavaScript. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

In ECMAScript5 (ES5 for short), there are three kinds of for loops, which are:

Simple for cycle

For-in

ForEach

In the ECMAScript6 (ES6) released in June 2015, a new loop was added:

For-of

Let's take a look at these four for loops.

Simple for cycle

Let's first take a look at one of the most common ways to write:

Const arr = [1,2,3]; for (let I = 0; I < arr.length; iTunes +) {console.log (arr [I]);}

When the array length does not change during the loop, we should store the array length as a variable for better efficiency. Here is an improved way to write it:

Const arr = [1,2,3]; for (let I = 0, len = arr.length; I < len; iTunes +) {console.log (arr [I]);} for-in

In general, we can use for-in to iterate through the contents of the array, as follows:

Const arr = [1,2,3]; let index;for (index in arr) {console.log ("arr [" + index + "] =" + arr [index]);}

In general, the running result is as follows:

Arr [0] = 1arr [1] = 2arr [2] = 3

But doing so often leads to problems.

The truth about for-in

The for-in loop iterates over the properties of the object, not the index of the array. Therefore, objects traversed by for-in are not limited to arrays, but can also be traversed. Examples are as follows:

Const person = {fname: "san", lname: "zhang", age: 99}; let info;for (info in person) {console.log ("person [" + info + "] =" + person [info]);}

The results are as follows:

Person [fname] = sanperson [lname] = zhangperson [age] = 99

It is important to note that the order in which for-in traverses attributes is uncertain, that is, the order of the output is independent of the order of the attributes in the object, the alphabetical order of the attributes, and any other order.

The truth about Array

Array is an object in Javascript, and the index of Array is the property name. In fact, the "array" in Javascript is misleading, and Array in Javascript is not like an array in most other languages. First of all, the Array in Javascript is not contiguous in memory, and second, the index of Array does not refer to the offset. In fact, the index of Array is not of type Number, but of type String. The reason we can correctly use words such as arr [0] is that the language can automatically convert 0 of Number type to "0" of String type. Therefore, there is never an index for Array in Javascript, but only attributes such as "0", "1", and so on. Interestingly, each Array object has a property of length, causing it to behave more like an array of other languages. But why didn't you output the property length when traversing the Array object? That's because for-in can only traverse "enumerable properties." length is a non-enumerable property. In fact, the Array object has many other properties that cannot be enumerated.

Now, going back to the example of looping an array with for-in, let's modify the previous example of traversing the array:

Const arr = [1,2,3]; arr.name = "Hello world"; let index;for (index in arr) {console.log ("arr [" + index + "] =" + arr [index]);}

The result of the operation is:

Arr [0] = 1arr [1] = 2arr [2] = 3arr [name] = Hello world

We see that for-in iterates through our new "name" property because for-in iterates through all the properties of the object, not just the "index." Also note that the index values output here, that is, "0", "1", and "2" are not of type Number, but of type String, because they are output as attributes, not indexes. Does that mean that instead of adding new properties to our Array object, we can just output the contents of the array? The answer is no. Because for-in not only traverses the properties of array itself, it also iterates through all the enumerable properties on the array prototype chain. Let's look at an example:

Array.prototype.fatherName = "Father"; const arr = [1,2,3]; arr.name = "Hello world"; let index;for (index in arr) {console.log ("arr [" + index + "] =" + arr [index]);}

The result of the operation is:

Arr [0] = 1arr [1] = 2arr [2] = 3arr [name] = Hello worldarr [fatherName] = Father

At this point, we can find that for-in is not suitable for traversing elements in Array, it is more suitable for traversing attributes in objects, which is why it was created in the first place. There is one exception, sparse arrays. Consider the following example:

Let key;const arr = []; arr [0] = "a"; arr [10000] = "c"; for (key in arr) {if (arr.hasOwnProperty (key) & & / ^ 0 $| ^ [1-9]\ d*$/.test (key) & key {console.log (data, index, array);})

Running result:

A 0 ["a", 3: "b", 10: "c", name: "Hello world"] b 3 ["a", 3: "b", 10: "c", name: "Hello world"] c 10 ["a", 3: "b", 10: "c", name: "Hello world"]

The index here is of type Number and does not traverse the properties on the prototype chain as for-in does.

Therefore, when using forEach, we do not need to declare index and traversal elements specifically, because these are used as arguments to the callback function.

In addition, forEach will iterate through all the elements in the array, but ES5 defines some other useful methods, here are some of them:

Every: the loop returns after * return false times

Some: the loop returns after * return true times

Filter: returns a new array whose elements satisfy the callback function

Map: processes the elements in the original array before returning them

Reduce: the elements in the array are processed in turn, and the result of the last processing is taken as the input of the next processing, and the final result is obtained.

ForEach performance

First of all, thanks to @ papa pa's reminder, I found that there was a mistake in my previous understanding.

You can take a look at jsPerf, the test results in different browsers are that forEach is not as fast as for. If you put the test code on the console, you may get different results, mainly because the console execution environment is different from the real code execution environment.

For-of

Let's take a look at an example:

Const arr = ['await,' baked,'c']; for (let data of arr) {console.log (data);}

The result of the operation is:

Abc

Why introduce for-of?

To answer this question, let's first take a look at the shortcomings of the three for loops before ES6:

ForEach cannot break and return

The disadvantage of for-in is even more obvious, it traverses not only the elements in the array, but also custom attributes, and even attributes on the prototype chain are accessed. Also, the order of traversing array elements may be random.

Therefore, in view of the above shortcomings, we need to improve the original for loop. But ES6 won't break the JS code you've already written. Currently, thousands of Web sites rely on for-in loops, some of which even use it for array traversal. If you want to add array traversal support by modifying the for-in loop, it will make all this more confusing, so the Standards Committee has added a new loop syntax to ES6 to solve the current problem, namely for-of.

So what exactly can for-of do?

Compared with forEach, it can correctly respond to break, continue, return.

The for-of loop supports not only arrays, but also most class array objects, such as DOM nodelist objects.

The for-of loop also supports string traversal, which traverses strings as a series of Unicode characters.

For-of also supports object traversal of Map and Set (both new types in ES6).

To sum up, the for-of loop has the following characteristics:

This is the most concise and straightforward syntax for traversing array elements.

This approach avoids all the shortcomings of the for-in loop.

Unlike forEach, it responds correctly to break, continue, and return statements.

It can traverse not only arrays, but also class array objects and other iterable objects.

It is important to note, however, that the for-of loop does not support normal objects, but if you want to iterate over the properties of an object, you can use the for-in loop (which is also its job).

* another way introduced by ES6 can also implement traversing the values of an array, which is Iterator. The previous example:

Const arr = ['averse,' baked,'c']; const iter = arr [Symbol.iterator] () Iter.next () / {value: 'averse, done: false} iter.next () / {value:' baked, done: false} iter.next () / / {value: 'centering, done: false} iter.next () / / {value: undefined, done: true} above is how to deeply understand the for cycle in JavaScript. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report