First of all, the traversal method is basically a for to traverse
1. forEach() traverses the array without returning a value
Used to call each element of the array, passing the element to the callback function. The original array remains unchanged. Executes the provided function once for each element of the array . no return value
The foreach method has three main parameters, which are the content of the array, the index of the array, and the array itself.
Same principle as a basic for loop
let arr= ['张三','李四','王五','老王','小明','小芳']
arr.forEach((value, index, arr)=> {
console.log(value, index, arr)
})
The value, index, and arr of the above code correspond to the contents of the array, the index of the array, and the array itself one by one
map and filter are basically the same
be careful:
1. If there is only one parameter, then it is the content of the array
2. It does not support break, continue and return statements in its statement structure. Break and continue will report an error directly and will not read the return statement.
3. array.length can output the length of the array
4. The usage scenario is traversal from beginning to end, if you take one of them, you need to
5. Pseudo arrays cannot be traversed using forEach
2. map() traverses the array, has a return value, and generates a new array according to the return value in the callback
let arr = [10, 3, 213, 23, 4, 234, 45]
// 将数组的每一个值*2,再生成一个新数组
let temp = []
temp = arr.map(function(value, index) {
return value * 2 // 返回array数组每一个值乘以2,并赋给temp
})
3. filter() traverses the array and has a return value
Determine whether the current item of the loop should be added to the returned new array according to the return value true or false
let array = ['a', 'b', 'c'];
let array = array.filter(function(ele,index,arr){
return arr.indexOf(ele) === index // 判断为true返回,为false则不返回
})
Usage scenario: query and delete
Notice:
1. filter() does not detect empty arrays
2. Does not change the original array
3. Return a new array
4. The principle is that if the execution result of the callback function is true, the value is stored in the array created inside the filter, and the array is finally returned. If it is false, it will not be returned.