簡體   English   中英

無法讀取JavaScript Array對象的undefined屬性“ includes”

[英]Cannot read property 'includes' of undefined for JavaScript Array object

這是我的代碼:

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
var result;

  for (var a = 0; a < nestedArr.length; a++) { // iterate nestedArr
    for (var b = 0; b < nestedArr[a].length; b++) {
      if (nestedArr[a+1].includes(nestedArr[a][b])) {
        result.push(nestedArr[a][b]);
    }
  }
}

輸出: Error: Cannot read property 'includes' of undefined 但是至少我可以確定幾件事:1. JavaScript中存在array的includes()方法。2.運行單個語句nestedArr[a+1]; 在控制台中給我數組[5, 2, 1, 4]

所以,我真的不明白Error嗎? 請幫我解決這個問題。 謝謝。

該程序將搜索不存在的索引。

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
  ...
    ...
      if (nestedArr[a+1].includes(nestedArr[a][b])) {
      // As nestedArr.length will return 2, the program will eventually  search for nestedArr[2+1 (=3)] which doesn't exist.
    }
  }
}

獎勵:為什么不在for var i in nestedArr而不是使用.length

看一下這個答案。

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
var result = [];

  for (var a = 0; a < nestedArr.length; a++) { // iterate nestedArr
    for (var b = 0; b < nestedArr[a].length; b++) {
      if (nestedArr[a].includes(nestedArr[a][b])) {
        result.push(nestedArr[a][b]);
    }
  }
}
console.log(result)

刪除加號就可以完成工作,基本上您嘗試訪問一個數組,但是沒有數組

正如@Nina Scholz所說

最后一個索引加一個不存在

您不需要按include進行檢查! 只需使用filtermap作為示例進行循環和分配!

 var nestedArr = [[1, 2, 3], [5, 2, 1, 4]]; var result = []; nestedArr.filter( (val) => { val.map( (v) => { result.push(v); } ) }) console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM