gpt4 book ai didi

javascript - i 没有在 while 循环中定义

转载 作者:行者123 更新时间:2023-12-03 03:00:02 24 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(var i = 0; i < newInv.length; i++) {
while(newInv[i][1] === newInv[i++][1]) {
newInv[i] += newInv[i++][0];
newInv.push([newInv[i][0], newInv[i][1]]);
newInv.splice(i,2);


}
}

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);

它一直给我错误 TypeError: newInv[(+ i)] is undefined 但我不确定为什么,因为 i 已定义,并且如果我只是尝试运行 newInv[ i] 我得到第一个结果。

JS Fiddle link

最佳答案

有几个地方需要修复。我更新了这个 jsfiddle

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 (var i = 0; i < newInv.length; i++) {
var j = i;
while (newInv[j + 1] && newInv[j][1] == newInv[j + 1][1]) {
newInv[j][0] += newInv[j + 1][0];
newInv.splice(j + 1, 1);
j++;
}
}

document.getElementById('test').innerHTML = newInv.join('<br>');
}

// 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);

https://jsfiddle.net/c3j8p2zu/7/

关于javascript - i 没有在 while 循环中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47445265/

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