gpt4 book ai didi

javascript - While 循环在第一次迭代时停止

转载 作者:行者123 更新时间:2023-12-01 02:43:03 25 4
gpt4 key购买 nike

我正在尝试添加匹配数组的所有数字并删除重复的名称。它适用于第一个实例,但 while 循环不会越过 Apples。

function updateInventory(arr1, arr2) {

function alphabetizer(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}

var newInv = arr1.concat(arr2).sort(alphabetizer);


for(i=0;i<newInv.length;i++){

while(newInv[i][1] != -1){
newInv[i][0] += newInv[i+1][0];
newInv.push([newInv[i][0], newInv[i][1]]);
newInv.splice(i,2);
return newInv;
}
return newInv;
}

return newInv;
}

// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"],
[10, "Apples"]
];

var newInv = [
[9, "Apples"],
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];

updateInventory(curInv, newInv);

所以当我运行这个时,我最终得到了

[[21,"Bowling Ball"],[67,"Bowling Ball"],[2,"Dirty Sock"],[1,"Hair Pin"],[2,"Hair Pin"],[3,"Half-Eaten Apple"],[5,"Microphone"],[7,"Toothpaste"],[19,"Apples"]]

最佳答案

问题是因为您正在从 while 循环返回。它终止循环的进一步执行。从 forwhile 循环中删除 return 部分。并且还使用 var 关键字声明变量 i,以使其作用域限于函数,而不是全局。

for(var i = 0; i < newInv.length; i++) {

while(newInv[i][1] != -1) {

newInv[i][0] += newInv[i+1][0];
newInv.push([newInv[i][0], newInv[i][1]]);
newInv.splice(i,2);

}

}

关于javascript - While 循环在第一次迭代时停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47431210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com