The difference between forEach, for and map

map method

 //值类型,不改变原数组,形成新的数组
 let valueArr = [11, 22, 33];
 let newArray = valueArr.map(item => item * 2);
 console.log(valueArr, newArray);  //[11,22,33]   [22,44,66]
 
 //引用类型,改变原数组
 let referArr = [{
    
     width: 100 }, {
    
     width: 200 }];
 referArr.map(item => item.editable = true);   
 console.log(referArr)  //[{width:100,editable:true},{width:200,eidtable:true}]

forEach method

 //值类型,不改变原数组,返回值undefined
 let valueArr = [11, 22, 33];
 let newArray = valueArr.forEach(item => item * 2);
 console.log(valueArr, newArray);  //[11,22,33]   undefined
 
 //若要改变值,则需配合index来使用
 let newArr1 = valueArr.forEach((item, index) => {
    
    
      valueArr[index] = item * 2;
 });
 console.log(valueArr, newArray);  //[22,44,66]   undefined
  
 //引用类型,改变原数组
 let referArr = [{
    
     width: 100 }, {
    
     width: 200 }];
 referArr.forEach(item => item.editable = true);   
 console.log(referArr)  //[{width:100,editable:true},{width:200,eidtable:true}]

Note:
Whether you use forEach or map to traverse the array, and use return to terminate the following statement, it is invalid in the loop. Variables are required as a transition value, but it is valid in the for loop.

const valids = []
let flag;
this.$refs[formName].forEach((item) => {
    
    
    item.validate((valid) => {
    
    
        !valid && (flag = true)
    })
})

Summary:
Both are used to traverse the array, forEach and map will execute the callback function for each element in the array.
The for loop is used to determine the length of the array, continue to terminate the current loop, and break to terminate the entire loop.
The map method can be chained programming, but it requires a return.
map: If the type of the array is a value type, a new array will be generated; if the type of the array is a reference type, the original array will be changed.
The basic principle of forEach is the for loop, and the return value is undefined.
forEach: If the type of the array is a value type, the original array will not be changed. If you want to change the original array, use the index parameter to change; if the type of the array is a reference type, the original array will be changed

Guess you like

Origin blog.csdn.net/m0_48076809/article/details/106590579