![](/img/trans.png)
[英]Trying to create copies of an array using spread operator, but some how the array is being mutated
[英]Array is getting mutated even after using spread operator
我正在嘗試創建我收到的原始數組的副本,作為傳遞給 function 的參數。 我正在對復制的數組執行操作,但我的主數組仍然發生突變。我不想更改我最初收到的 cid 的值。 我已經嘗試了很多方法,比如通過 slice()、concat() 和擴展運算符進行復制,但我的主 (cid) 數組仍然發生了變異。 幫我擺脫這個。 提前致謝..
let copierFunction=(...a)=>{
let b= [...a]
return(b)
}
let originalCID = cid.filter((e)=>{
if(e){
return e
}
})
let cashInDrawer=copierFunction(...cid);
let toBeReturned = cash-price;
let currencyRefrence= [['PENNY',0.01],['NICKEL',0.05],['DIME',0.1],['QUARTER',0.25],['ONE',1],['FIVE',5],['TEN',10],['TWENTY',20],['ONE HUNDRED',100]];
currencyRefrence = currencyRefrence.reverse()
let change=[]
function returnChange(a){
if(a==0){
return null;
}
for(let i=0;i<currencyRefrence.length;i++){
let returnUnit = a / currencyRefrence[i][1]
if(returnUnit>=1){
let chutte = parseInt(returnUnit)*currencyRefrence[i][1];
for(let j=0;j<cashInDrawer.length;j++){
if(cashInDrawer[j][0] == currencyRefrence[i][0]){
if(cashInDrawer[j][1]>=currencyRefrence[i][1]){
if(cashInDrawer[j][1]>chutte){
change.push([cashInDrawer[j][0],chutte])
a= a-chutte;
a= a.toFixed(2)
cashInDrawer[j][1]= cashInDrawer[j][1]-chutte
return returnChange(a);
}else{
change.push([cashInDrawer[j][0],cashInDrawer[j][1]])
a= a-cashInDrawer[j][1];
a= a.toFixed(2)
cashInDrawer[j][1]= 0;
return returnChange(a);
}
}
}
}
}
}
}
returnChange(toBeReturned);
function statusChecker(cashInDrawer,change){
//checking if change is given or not.
let returnedAmount=(change.reduce((a,e)=>{
return( a + e[1])
},0)).toFixed(2)
if(toBeReturned > returnedAmount ){
return 'INSUFFICIENT_FUNDS'
}
//checking if cashInDrawer is empty after change.
let amountIncashInDrawer = (cashInDrawer.reduce((a,e)=>{
return( a + e[1])
},0)).toFixed(2)
if(amountIncashInDrawer==0){
return 'CLOSED'
}
return 'OPEN';
}
let status = statusChecker(cashInDrawer,change)
if(status =='INSUFFICIENT_FUNDS'){
return {status:status,change:[]}
}
if(status == 'CLOSED'){
return {status:status,change: 'originalCID'}
}
return {status:'OPEN',change:change}
}
console.log(checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])); ```
JS arrays 是通過引用傳遞的。 你需要使用:
let arrayCopy = JSON.parse(JSON.stringify(array));
這樣您就可以對 arrayCopy 進行操作,而您的原始數組不會改變
JS arrays 是 memory 中的簡單對象,當在第一個 class 函數中作為參數傳遞時,它的引用將被傳遞。 因此,對該引用數組的任何更改也會更改實際數組的值。 相反,您可以創建一個新數組並傳播語法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.