繁体   English   中英

未捕获的TypeError:无法读取未定义的属性“ 1”

[英]Uncaught TypeError: Cannot read property '1' of undefined

我正在使用清单功能,但是,我不断收到错误:Uncaught TypeError:无法读取未定义的属性“ 1”。 我不认为我要遍历数组的长度,所以为什么我会得到“属性'1'未定义”。 显然,我正在尝试读取其中不存在的内容。我只是看不到它。任何帮助表示赞赏。我使用console.log尝试记录错误。但是一切都返回了输出。谢谢

 function updateInventory(arr1, arr2) { // All inventory must be accounted for or you're fired! for(var i = 0; i < arr1.length; i++) { //if item found, update var index = findItem(arr1[i][1], arr2); if(index != undefined) { arr1[i][0] += arr2[i][0]; } else { arr1.push(arr2[index]); } } //sort arr1 arr1.sort(function(first, second) { return (first[1] > second[1]) ? 1 : -1; }); return arr1; } //helper method to search arr2 function findItem(item, arr2) { for(var i = 0; i < arr2.length; i++) { if(item === arr2[i][1]) return i; } return undefined; } // Example inventory lists var curInv = [ [21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"] ]; var newInv = [ [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"] ]; updateInventory(curInv, newInv); 

在其他代码中else { arr1.push(arr2[index]); } else { arr1.push(arr2[index]); } index在这里将是未定义的。 这将导致未定义的内容被推入arr1,并且您正在同一数组上运行循环。 因此var index = findItem(arr1[i][1], arr2)将给出您看到的错误。 如果用更新后的值更新另一个数组会更好。

 function updateInventory(arr1, arr2) { // All inventory must be accounted for or you're fired! for(var i = 0; i < arr1.length; i++) { //if item found, update var index = findItem(arr1[i][1], arr2); if(index != undefined) { arr2[index][0] += arr1[i][0]; }else{ arr2.push(arr1[i]); } } //sort arr2 arr2.sort(function(first, second) { return (first[1] > second[1]) ? 1 : -1; }); return arr2; } //helper method to search arr2 function findItem(item, arr2) { for(var i = 0; i < arr2.length; i++) { if(item === arr2[i][1]) return i; } return undefined; } // Example inventory lists var curInv = [ [21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"] ]; var newInv = [ [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"] ]; console.log(updateInventory(curInv, newInv)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM