使用 Array.map() 方法时出现奇怪的错误。为什么 arrayElementLength=strarr[index+1].length 抛出一个未定义的错误(即使它有效)
function longestConsec(strarr, k) {
// your code
let solution = [];
strarr.map((string, index, arr) => {
let arrayElementLength = strarr[index+1].length;
console.log(arrayElementLength);
if(string.length == arrayElementLength){
solution.push(string);
}
});
return solution;
}
console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))
最佳答案
当您到达 strArr
的最后一个索引而不是 index+1
时,您正在尝试访问数组中不存在的索引,这是导致此错误 strarr[(index + 1)] 未定义
function longestConsec(strarr, k) {
// your code
let solution=[];
strarr.map((string,index,arr)=>{
let arrayElementLength=strarr[index+1].length;
console.log(arrayElementLength);
if(string.length==arrayElementLength){
solution.push(string);
}
})
return solution;
}
console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))
旁注:您没有使用 map 的返回值,因此最好使用 forEach
关于javascript - 为什么 Array.map() 方法返回 arr[index+1].length 为未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54493433/