Home  >  Article  >  Web Front-end  >  Similarities and differences between foreach, for in, for of

Similarities and differences between foreach, for in, for of

不言
不言Original
2018-07-07 10:54:371771browse

This article mainly introduces the similarities and differences between foreach, for in, and for of. It has certain reference value. Now I share it with you. Friends in need can refer to the

forEach() method. Used to call each element of the array and pass the element to the callback function.

Note: forEach() will not execute the callback function for an empty array.

Sample code:

1 var arr = [4, 9, 16, 25];
2 arr.forEach(function(value, index) {
3     console.log(index+': '+value+'\n');
4 });

##The results are as follows:

The for/in statement is used to loop through object properties.

Every time the code in the loop is executed, an operation will be performed on the elements of the array or the properties of the object.

Sample code:

1 var person = {
2     name: 'jack',
3     age: 18,
4     gender: 'male'
5 };
6 for(key in person) {
7     console.log(key+': '+person[key]+'\n');
8 }

##The results are as follows

:

It should be noted that if you use the for in statement to traverse the array, the following problems may occur:

 1. The index is of string type and cannot directly perform geometric operations.

 2. The traversal order may not be according to the internal order of the actual array.

 3. Using for in will traverse all enumerable properties of the array, including prototypes.

As shown below

:

1 var arr = [12, 43, 19];
2 Array.prototype.index = 110;//这里的原型属性也会被打印出来
3 for(var index in arr) {
4     console.log(index+': '+arr[index]+'\n');
5 }

##Running result

:

The for of statement is more convenient to use than the for in statement. It is a newly proposed way of traversing arrays in ES6.

Specific use

:

1 var arr = [12, 43, 19];
2 Array.prototype.index = 110;//此原型属性不会被打印出来
3 for(var value of arr) {
4     console.log(value+'\n');
5 }

##The results are as follows

:

Overview: foreach More are used to traverse arrays, but the use is more complicated; for in is generally used to traverse

objects; for of is very convenient and safer to use to traverse arrays. The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

JS asynchronous programming Promise, Generator, async/await

var, let, The difference between const


The above is the detailed content of Similarities and differences between foreach, for in, for of. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn