JavaScript 算法和数据结构项目 - 计算找零

``````   **你目前的代码**
``````
``````function checkCashRegister(price, cash, cid) {
var total=0;
var change=cash-price;
var arr=[0.01,0.05,0.1,0.25,1,5,10,20,100];
var result=[];
for (let i=0;i<cid.length;i++){
total+=cid[i][1];
};
if (total<change) {
return {status: "INSUFFICIENT_FUNDS", change: []};
};
if(total===change){
return {status: "CLOSED", change: [...cid]};
};
for (let i=arr.length-1;i>0;i--){
if (arr[i-1]<change<arr[i]){
if (change>=cid[i-1][1]){
result.push(cid[i-1]);
change-=cid[i-1][1];
}else {
result.push([cid[i-1][0],arr[i-1]*Math.floor(change/arr[i-1])]);
change-=arr[i-1]*Math.floor(change/arr[i-1]);
};
if (change===0){
return {status: "OPEN", change: [...result]};
}
}
}
return {status: "INSUFFICIENT_FUNDS", change: []};
}

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]]);
``````
``````   **你的浏览器信息：**
``````

``````arr[i-1] < change && change < arr[i]
``````

``````arr[i-1] < change
``````

``````change = (change - cid[i-1][1]).toFixed(2);
``````

Oshibuki 和 iLtc 的讲解很到位了，关于 iLtc 中判断条件修改后

``````for (let i = arr.length; i > 0; i--)
``````

ps: 当然用 `for (let i = arr.length - 1; i >= 0; i--)` 的循环也可以，只是后面的用到 `arr[i - 1]` 都需要修改，取决于你。循环只要满足“循环不变”原则不漏掉元素就行。