javascript - 为什么 Array.map() 方法返回 arr[index+1].length 为未定义?

标签 javascript arrays

使用 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/

相关文章:

java - : System. arraycopy 或 Arrays.copyOf 哪个更有效?

javascript - Jquery Mobile - $.mobile.changepage 不加载外部 .JS 文件

javascript - 多选复选框下拉菜单在选中和取消选中时调用事件

javascript - 替换内置函数的原型(prototype)是否非法?

javascript - React/Redux 存储状态未保存

java - 从二维坐标数组创建一条路径供 AI 遵循

c++ - 如何在 C++ 中调用 void foo(int (&)[]) {}?

javascript - Express:有必要用status 200响应吗?

ios - Swiftt3:如果不重复,则追加到数组的扩展

c# - P/Invoke [In, Out] 属性对于编码(marshal)处理数组是可选的吗?