Learn more about the For loop in JavaScript

Source: Internet
Author: User
Tags hasownproperty

In ECMAScript5 (referred to as ES5), there are three for loops, respectively:

Simple for loop
For-in
Foreach
In the June 2015 release of ECMASCRIPT6 (abbreviated ES6), a new cycle was added:

for-of
Let's take a look at these 4 for loops.

Simple for loop

Let's take a look at the most common wording:

Const ARR = [1, 2, 3];
for (Let i = 0; i < arr.length; i++) {
Console.log (Arr[i]);
}
When the length of the array does not change in the loop, we should store the length of the array in variables so that it will be more efficient, and the following is an improved notation:

Const ARR = [1, 2, 3];
for (Let i = 0, len = arr.length; i < Len; i++) {
Console.log (Arr[i]);
}
For-in

Normally, we can use for-in to iterate through the contents of an array, with the following code:

Const ARR = [1, 2, 3];
Let index;
For (index in arr) {
Console.log ("arr[" + index + "] =" + Arr[index]);
}
In general, the results of the operation are as follows:

Arr[0] = 1
ARR[1] = 2
ARR[2] = 3
But there are often problems in doing so.

The truth of For-in

The for-in loop iterates through the properties of the object, not the index of the array. As a result, objects traversed by for-in are not limited to arrays, but can also traverse objects. Examples are as follows:

Const PERSON = {
fname: "San",
LName: "Zhang",
age:99
};
let info;
for (info) {
Console.log ("person[" + info + "] =" + Person[info]);
}
The results are as follows:

Person[fname] = San
Person[lname] = Zhang
Person[age] = 99
It is important to note that the order of the For-in traversal properties is not deterministic, that is, the output order is independent of the order of the attributes in the object, and is independent of the alphabetical order of the properties, regardless of any other order.

The truth of Array

The array is an object in Javascript, and the index of the array is the property name. In fact, "array" in JavaScript is somewhat misleading, and the array in JavaScript is not like an array of most other languages. First, the array in Javascript is not contiguous in memory, and secondly, the index of the array does not refer to the offset. In fact, the index of an Array is not a number type, but a String type. The reason we can correctly use the notation like arr[0] is that the language can automatically convert the number type of 0 to a String of type "0″." So, Kings Www.jsgren.com never had an Array index in Javascript, and only attributes like "0″," 1″, and so on. Interestingly, each array object has a property of length that causes it to behave more like an array of other languages. But why does it not output the length property when traversing the Array object? That's because for-in can only traverse "enumerable properties", length is a non-enumerable property, and in fact, the Array object has many other non-enumerable properties.

Now, let's go back to the example of looping an array with for-in, and we'll modify the example of the previous traversal of the array:

Const ARR = [1, 2, 3];
Arr.name = "Hello World";
Let index;
For (index in arr) {
Console.log ("arr[" + index + "] =" + Arr[index]);
}
The operating result is:

Arr[0] = 1
ARR[1] = 2
ARR[2] = 3
Arr[name] = Hello World
We see that the for-in loop accesses our new "name" property, because for-in iterates through all the properties of the object, not just the index. It is also important to note that the index value that is output here, that is, "0″," "1″," 2″ is not of type number, but is of type String, because it is output as an attribute, not an index. Does that mean that we can just output the contents of the array without adding a new attribute to our array object? The answer is in the negative. Because for-in not only iterates through the properties of the 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 operating result is:

Arr[0] = 1
ARR[1] = 2
ARR[2] = 3
Arr[name] = Hello World
Arr[fathername] = Father
Writing here, we can find that for-in is not suitable for iterating through the elements in an Array, which is more appropriate for traversing the properties in an object, which is what it was created for. In one case, the sparse array is the exception. Consider the following example:

Let key;
Const ARR = [];
Arr[0] = "a";
ARR[100] = "B";
ARR[10000] = "C";
For (key in arr) {
if (Arr.hasownproperty (key) &&
/^0$|^[1-9]\d*$/.test (Key) &&
Key <= 4294967294
) {
Console.log (Arr[key]);
}
}
For-in only iterates through the entities that exist, in the example above, for-in traversed 3 times (traversing the elements of "0″," "100″," 10000″, and the normal for loop 10,001 times). So, as long as it's done properly, for-in can play a huge role in traversing the elements in the Array.

To avoid duplication of effort, we can package the above code:

function Arrayhasownindex (array, prop) {
Return Array.hasownproperty (prop) &&
/^0$|^[1-9]\d*$/.test (prop) &&
Prop <= 4294967294; 2^32-2
}
Examples of use are:

For (let key in arr) {
if (Arrayhasownindex (arr, key)) {
Console.log (Arr[key]);
}
}
For-in Performance

As mentioned above, each iteration of an operation searches for an instance or prototype attribute, and each iteration of the for-in loop generates more overhead, so it is slower than the other loop types, and the average speed is 1/7 of the other types of loops. Therefore, you should avoid using for-in loops unless you explicitly need to iterate over an object with an unknown number of attributes. If you need to traverse a limited list of known attributes, it is quicker to use other loops, such as the following example:

Const OBJ = {
"Prop1": "Value1",
"Prop2": "value2"
};

Const PROPS = ["Prop1", "PROP2"];
for (Let i = 0; i < props.length; i++) {
Console.log (Obj[props[i]);
}
In the code above, the properties of the object are stored in an array, and each property is looked up relative to for-in, which only focuses on the given property, saving the overhead and time of the loop.

Foreach

In ES5, a new loop, the ForEach loop, is introduced.

Const ARR = [1, 2, 3];
Arr.foreach (data) = {
Console.log (data);
});
Operation Result:

1
2
3
The ForEach method executes the callback function once for each item that has a valid value in the array, those that have been deleted (using the Delete method, and so on), or items that have never been assigned are skipped (excluding those whose values are undefined or null). The callback function is passed three arguments in turn:

The value of the current item of the array;
The index of the current item of the array;
The array object itself;
It is important to note that the scope of the ForEach traversal is determined before the first call to callback. Items added to the array after the call to foreach are not accessed by callback. If a value that already exists is changed, the value passed to callback is the value that the ForEach iterates over to their moment. Deleted items are not traversed to.

Const ARR = [];
Arr[0] = "a";
ARR[3] = "B";
ARR[10] = "C";
Arr.name = "Hello World";
Arr.foreach (data, index, array) = = {
Console.log (data, index, array);
});
Operation Result:

A 0 ["a", 3: "B", Ten: "C", Name: "Hello World"]
B 3 ["A", 3: "B", Ten: "C", Name: "Hello World"]
C Ten ["A", 3: "B", "C", Name: "Hello World"]
The index here is the number type and does not traverse the properties on the prototype chain like For-in.

Therefore, when using ForEach, we do not need to specifically declare the index and traversed elements, as these are the parameters of the callback function.

In addition, ForEach will iterate through all the elements in the array, but ES5 defines some other useful methods, the following is a partial:

Every: Loop returns after the first return false
Some: Loop returns true after the first return
Filter: Returns a new array of elements within the array that satisfy the callback function
Map: The elements in the original array are processed and returned
Reduce: The elements in the array are processed sequentially, the last processing result is the input of the next processing, and the final result is obtained.
ForEach Performance

First of all thanks to @papa Pa's reminder, only to find that my previous understanding has been wrong.

You can look at JsPerf, the result of testing under different browsers is that the speed of forEach is not as good as for. If you put the test code on the console, you might get a different result, mainly because the console execution environment differs from the actual code execution environment.

for-of

Let's look at an example:

Const ARR = [' A ', ' B ', ' C '];
For (let data of arr) {
Console.log (data);
}
The operating result is:

A
B
C
Why should we introduce for-of?

To answer this question, let's take a look at the flaws in the 3 for loops before ES6:

ForEach cannot break and return;
The for-in disadvantage is even more obvious, which not only iterates through the elements in the array, but also iterates through the custom properties and even the properties on the prototype chain are accessed. Also, the order in which the array elements are traversed may be random.
So, given all these flaws, we need to improve the original for loop. But ES6 won't spoil the JS code you've written. Currently, thousands of Web sites rely on for-in loops, some of which even use them for array traversal. If you want to increase the array traversal support by modifying the for-in loop, it will make all this more confusing, so the standard committee has added a new cyclic syntax to ES6 to solve the current problem, namely for-of.

What the hell is for-of going to do?

The correct response to break, continue, and return is compared to ForEach.
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 treats a string as a series of Unicode characters to traverse.
For-of also supports Map and Set (both are new types in ES6) object traversal.
To summarize, the for-of cycle has several characteristics:

This is the simplest and most straightforward syntax for iterating over an array element.
This method avoids all defects in the for-in cycle.
Unlike ForEach, it can correctly respond to break, continue, and return statements in the Golden Silk Court .
It is not only possible to iterate through an array, but also to traverse a class array object and other objects that can iterate.
However, it is important to note that the for-of loop does not support ordinary objects, but if you want to iterate over the properties of an object, you can use the
The for-in loop (which is also its job).

The last thing to say is that ES6 introduces another way to implement the value of traversing an array, that is Iterator. Last Example:

Const ARR = [' A ', ' B ', ' C '];
Const ITER = Arr[symbol.iterator] ();

Iter.next ()//{value: ' A ', done:false}
Iter.next ()//{value: ' B ', done:false}
Iter.next ()//{value: ' C ', done:false}
Iter.next ()//{value:undefined, done:true}
However, this content beyond the scope of this article, and Iterator to talk about a lot, and later have time to write an article to introduce, welcome attention.

Learn more about the For loop in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.