Definitions and Usage
The map() method returns a new array whose elements are the values processed by the call to the original array element.
- Return a new array (map); return a new array (map); return a new array.
Error model
let arr = [{a:1,b:2},{a:2,b:3}];
let newArr = arr.map(v => {
v.a += 1;
v.b += '1';
return v
});
console.log(arr); // [{a:2,b:'21'},{a:3,b:'and'}]
console.log(newArr); // [{a:2,b:'21'},{a:3,b:'and'}]
Copy the code
- Feel it at will. It’s devastating.
Analysis of the
- This is due to the fact that the array returns a processed object, and the js reference type does not change at all. The change (v) is equal to the change of v pointing to the same address.
- So it’s easy to figure out why, so the first thing that comes to mind is assign
- The object.assign () method is used to copy the values of all enumerable properties from one or more source objects to target objects. It will return the target object.
- I’ll think about the rest when I don’t work overtime.
let arr = [{a:1,b:2},{a:2,b:3}];
let newArr = arr.map(v => {
let v1 = Object.assign({},v);
v1.a += 1;
v1.b += '1';
return v1
});
console.log(arr); // [{a:1,b:2},{a:2,b:3}]
console.log(newArr); // [{a:2,b:'21'},{a:3,b:'and'}]
Copy the code