为什么我的函数将total属性附加到所有单独的数组?

时间:2019-05-13 14:35:06

标签: javascript arrays slice

我有3个数组,它们使用slice()互相复制。声明每个属性后,我仅将一个名为“ total”的属性附加到数据数组。当我控制台日志时,所有声明的数组都具有新的属性“ total”。为什么是这样?应该具有total属性的唯一变量是data。我使用slice是因为它为每个变量创建了一个新的单独的数组。

 const cData = (4093) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, …];
  //Side note: cData is actually an array of objects with key values
  //cData[2] would look like the below code.
  {Area: "NORTHEAST AREA", District: "CONNECTICUT CS 
  DISTRICTCT", Unit: "WORTHINGTON", Finance Number: "249656", Zip: 
  "01026", …}

 const data = cData.slice();
 var dataArea = data.slice();

 data[2]['total'] = 22; //When I console log all 3 variables have 
                        //total attribute appended

 console.log(cData[2]);            //When I console.log, all 3 variables 
 console.log(data[2]); //have total attribute appended
 console.log(dataArea[2]);

为什么会这样? Slice为每个变量创建新的数组。我期望只有变量“数据”会附加总数。

1 个答案:

答案 0 :(得分:0)

由于slice正在创建原始数组的浅表副本,因此您可以使用JSON.parseJSON.stringify创建深表副本,然后向该数组添加新键

let cData = [{
  Area: "NORTHEAST AREA",
  District: "CONNECTICUT CS DISTRICTCT",
  Unit: "WORTHINGTON ",
  FinanceNumber: "249656 ",
  Zip: "01026"
}, {
  Area: "NORTHEAST AREA",
  District: "CONNECTICUT CS DISTRICTCT",
  Unit: "WORTHINGTON ",
  FinanceNumber: "249656 ",
  Zip: "01026"
}, {
  Area: "NORTHEAST AREA",
  District: "CONNECTICUT CS DISTRICTCT",
  Unit: "WORTHINGTON ",
  FinanceNumber: "249656 ",
  Zip: "01026"
}]

const data = JSON.parse(JSON.stringify(cData))

data[2]['total'] = 22;

console.log(cData[2]);
console.log(data[2]);