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

时间:2017-09-08 15:54:35

标签: javascript arrays function

我正在处理库存功能,但是,我一直收到错误:未捕获的TypeError:无法读取属性' 1'未定义的。我不认为我会超过阵列的长度,所以为什么我会得到"属性' 1'未定义&#34 ;.显然,我试图阅读的东西不存在。我无法看到它。任何帮助赞赏。我使用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);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

代码else { arr1.push(arr2[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));