Js array traversal, basically for, for in, foreach, for of, map, etc
let arr = [1.2.3.4.5];
Copy the code
1. Plain for loops
for(j = 0; j < arr.length; j++){
}
Copy the code
2. Optimized for loop
for(j = 0,len=arr.length; j < len; j++) {
}
Copy the code
3. The foreach loop
arr.forEach((num, index) = > {
return arr[index] = num * 2;// arr = [2, 4, 6, 8, 10]
});
Copy the code
4. Map traverse
let doubled = arr.map(num= > {
return num * 2;// doubled = [2, 4, 6, 8, 10]
});
Copy the code
The difference between forEach and map: forEach() does not return the result of execution, but undefined. That is, forEach() will modify the original array. The map() method takes a new array and returns it.
5. For in loop
//for-in iterates through the array's properties
arrTmp.name= "myTest" ;
for ( var i in arrTmp){
console.log(i+ ":" +arrTmp[i])
}
0:value1 1:value2 2:value3 Name :myTest
Copy the code
- Traversing an object’s properties is the least forin efficient.
- The value that I’m iterating over is zero
key
. - You can’t iterate
map/set
. - You can iterate over a number.
6. For of loop
// for-of traverses the string
let iterable = "China China" ;
for ( let value of iterable) {
console.log(value);
}
// Output "c" "h" "I" "n" "a" "Chinese" "country"
Copy the code
In ES6, for-of traversal is added. It is designed to iterate over collections of arrays of classes, such as DOM NodeList objects, Maps and sets, and even strings. The official line:
for… The of statement creates an iteration loop over iterable objects (including Array, Map, Set, String, TypedArray, Arguments, and so on), calling a custom iteration hook with an execution statement for each property value of a different property