简体   繁体   English

修改复制的数组而不修改原始数组js

[英]Modify copied array without modifying the original array js

function checkCashRegister(price, cash, cid) {
  let payBackAmount = cash - price;
  let tempArr = cid.slice();

  for (let i = 0; i < tempArr.length; i++) {
    tempArr[i][1] = 0;
  }
  console.log("cid is", cid);
}
checkCashRegister(19.5, 20, [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],

  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100],
]);

Here I am trying to copy an array from the parameterized function.在这里,我试图从参数化的 function 中复制一个数组。 cid is the array which I am trying to pass inside the function and I am trying to copy it into tempArr . cid是我试图在 function 中传递的数组,我试图将它复制到tempArr中。 Later when modifying the values of tempArr , the values of cid is changing as well.稍后在修改tempArr的值时, cid的值也会发生变化。 I have also tried copying the values using let tempArr=[...cid] and let tempArr=cid.slice(0)我也尝试使用let tempArr=[...cid]let tempArr=cid.slice(0)复制值

Here in the above code when you are copying one array to an other array the slice method and spread operator from javascript does a shallow copy, for your usecase you might want to do a deep clone of the object you can do let tempArr = JSON.parse(JSON.stringify(cid)) , instead of this you can also use deepClone from Lodash to deep clone a object在上面的代码中,当您将一个数组复制到另一个数组时,javascript 中的切片方法和扩展运算符执行浅拷贝,对于您的用例,您可能想要对 object 进行深度克隆,您可以let tempArr = JSON.parse(JSON.stringify(cid)) ,您也可以使用deepClone的 deepClone 来深度克隆 object

also please look at this thread What is the difference between a deep copy and a shallow copy?也请看这个线程深拷贝和浅拷贝有什么区别? to know more about shallow clone and deep clone了解更多关于浅克隆和深克隆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM