简体   繁体   中英

Cannot read property 'includes' of undefined for JavaScript Array object

Here are my code:

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

Output: Error: Cannot read property 'includes' of undefined . But at least I can make sure several things: 1. includes() method exists for array in JavaScript 2. Run a single statement nestedArr[a+1]; in console give me the array [5, 2, 1, 4]

So, I really don't understand the Error ? Please help me figure out this. Thanks.

The program will search for an index that doesn't exist.

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.
    }
  }
}

Bonus: Why not use for var i in nestedArr instead of using .length

Take a look at this answer.

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)

removing the plus one did the job, basically you tried to access an array were no arrays were present

As @Nina Scholz commented

the last index plus one does not exist

You don't need to check by includes ! Just do loop and assign using filter and map as example !!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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