function checkCashRegister(price, cash, cid) { let amount = { "ONE HUNDRED": 100, "TWENTY": 20, "TEN": 10, "FIVE": 5, "ONE": 1, "QUARTER": 0.25, "DIME": 0.1, "NICKEL": 0.05, "PENNY": 0.01 } let copy = cid.slice(); let sum = cid.map(el => (el[1])).reduce((a, b) => (a + b)); let changeDue = cash - price; let newArr = []; let result = {}; if (sum === changeDue) { result.status = 'CLOSED'; result.change = copy; } for (let i = cid.length - 1; i >= 0; i--) { let count = 0; let unit = amount[cid[i][0]]; while (unit <= changeDue && unit <= cid[i][1]) { changeDue -= unit; cid[i][1] -= unit; count++; } newArr.push([cid[i][0], count * unit]); } return result; } 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] ]));
Hello, I am trying to solve a problem that I should print the status and the amount of change.
(您好,我正在尝试解决一个问题,我应该打印状态和更改量。)
I am in the middle of process, and I have a method related question. (我正在处理过程中,我有一个与方法有关的问题。)
Since if the amount of the money cash machine has is the same as cash subtracted by price, I should print "status: close" and the money, I copied the "cid" array(which is input) with slice()
method so that It does not affect the "cid" that I am going to use in the other condition where I use it to calculate the amount of change.
(由于如果现金提款机的数量与现金减去价格后的数量相同,那么我应该打印“ status:close”和货币,因此我使用slice()
方法复制了“ cid”数组(输入),以便它不会影响在其他情况下使用“ cid”来计算更改量的情况。)
so to check if the closed status works well, I printed it, and I expected PENNY to be 0.5 but, for some reason, it has been affected by the code below if-statement(for loop part) and the PENNY part is 0.000XXX.
(因此,要检查关闭状态是否工作正常,我将其打印出来,并希望PENNY为0.5,但由于某种原因,它已受到if-statement(用于循环部分)下面的代码的影响,并且PENNY部分为0.000XXX 。)
so when I tried to move the return statement right below the if-statement. (因此,当我尝试将return语句移至if语句下方时。)
it worked as I expected. (它按预期工作。)
My question is I expected the for loop neither to affect nor to be affected because slice()
methods does not alter the original arry(cid), but it did not work as I expected.
(我的问题是我希望for循环既不会影响也不会受到影响,因为slice()
方法不会更改原始的arry(cid),但是它没有按我预期的那样工作。)
Can anyone figure out why?
(谁能找出原因?)
ask by SH Kim translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…