This article mainly shares with you examples of common methods of JS array traversal. There are three methods in this article. I hope it can help you.
First type: for loop
for(var i=0 , len= arr.length ; i<len ; i++){ 代码块 }
Second type: forEach
var arr=[12,14,15,17,18]; var res=arr.forEach(function(item,index,input){ input[index]=item*10; }); console.log(res); //undefined console.log(arr); //会对原来的数组产生改变
Parameter description: item: current item in the array
Index: current Index of item
Since the original array input The value has not changed)
var arr=[12,14,15,17,18]; var res=arr.forEach(function(item,index,input){ return item*10; }); console.log(res); //undefined console.log(arr); //[12,14,15,17,18]没变
If the array is modified in the anonymous function, it will be modified to the
var arr=[12,14,15,17,18]; var res=arr.map(function(item,index,input){ return item*10; }); console.log(res); //[120,140,150,170,180] console.log(arr); //[12,14,15,17,18]
# Important note: There is a return value (if no return value is given, res is undefined, but res is indeed an array. As long as the input is changed, the original array will change)
var arr=[12,14,15,17,18]; var res=arr.map(function(item,index,input){ input[index]=item*10; }); console.log(res); //[undefined, undefined, undefined, undefined, undefined] console.log(arr); //[120,140,150,170,180]
Other notes: Anonymous functions this points to Windows
If the array is modified in the anonymous function, it will be modified to the original array
The above is the detailed content of Examples of common methods for array traversal in JS. For more information, please follow other related articles on the PHP Chinese website!