We have a piece of code like this
// 构建数据
let obj = {name: '名字' ,age: 18};
let list = [];
for(let i=0; i<60; i++) list.push(obj)
// 开始处理数据
let Arr = [];
let cloneArr = [];
for(let j=0; j<2; j++) Arr.push(cloneArr)
list.map((item,inx) => {
if(inx < 50) Arr[0].push(item);
else if(inx >= 50 && inx < 100) Arr[1].push(item);
})
console.log(Arr)
Our ideal state should be like this
But the actual result is
There is a problem of pointing to the array inside and copy assignment. When we dynamically generate the internal array for Arr through the for loop, what we push here is the array variable cloneArr declared in advance. In the map loop below, whether it is the operation of Arr[0 ] or Arr[1], both are operating the array variable cloneArr, Arr[0], Arr[1] all point to cloneArr, in order to solve this problem, we can use the following two when dynamically pushing the array inside Arr Way:
1. We directly use deep copy to assign values to it, and operate the internal array of Arr in the map loop. Their pointers will not point to the array variable cloneArr due to the deep copy effect.
Arr.push(JSON.parse(JSON.stringify(cloneArr)))
2. Abandon cloneArr, each push directly creates a new array, and there will be no pointing and copying functions
Arr.push([])
Tips: Many people will encounter such problems in the details at work, but many people don't understand it. In fact, as long as they understand the principle, it is actually very simple.