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

时间:2019-02-02 13:16:56

标签: 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))

5 个答案:

答案 0 :(得分:2)

当您到达strArr的最后一个索引而不是index+1时,您正在尝试访问数组中不存在的索引,这是此错误strarr[(index + 1)] is undefined的原因

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

答案 1 :(得分:2)

  

为什么arrayElementLength = strarr [index + 1] .length会抛出一个错误,即未定义(即使它可以工作)

否,它在上一次迭代中不起作用。数组索引从0开始。使用strarr[index+1],在上一次迭代中,您的代码尝试从实际上不存在的索引中访问该项,并返回undefined

var sampleArr = ['test'];
console.log(sampleArr[0]); //test
console.log(sampleArr[1]); //undefined

因此,从索引部分删除+1,您的代码将按预期工作:

function longestConsec(strarr, k) {
    // your code
    let solution=[];
    strarr.map((string,index,arr)=>{
      let arrayElementLength=strarr[index].length;
      console.log(arrayElementLength);
      if(string.length==arrayElementLength){
          solution.push(string);
      }
    })
    return solution;
}

console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))

答案 2 :(得分:0)

这并不奇怪,数组索引从0开始,因此最后一个索引+ 1将是不确定的。
此外,Array.map通常用于将给定数组“映射”到新数组,您使用它的方式更适合使用Array.forEach

function longestConsec(strarr, k) {
  let solution = [];
  strarr.forEach((string, index, arr) => {
    let arrayElementLength = strarr[index].length;
    console.log(arrayElementLength);
    if(string.length === arrayElementLength){
      solution.push(string);
    }
  })
  return solution;
}

console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))

答案 3 :(得分:0)

正如其他人已经提到的那样,当循环到达最后一个元素时,您会收到错误消息。 strarr[index+1]返回undefined,您将无法访问它的length

查看您的代码,如果您打算获取与下一个元素具有相同length的所有项目,则filter更适合您的目的:

function longestConsec(strarr, k) {
  return strarr.filter((string, index) => {
    return index !== strarr.length - 1
            && string.length === strarr[index + 1].length
  })
}

console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))

如果循环遇到了最后一个元素,我还添加了一个额外的检查index !== strarr.length - 1

答案 4 :(得分:0)

Array.map遍历映射中的每个元素,index(第二个参数)是当前索引,现在,如果到达要映射的数组中的最后一个元素,则下一个元素( index + 1)根本不存在。

如果整个函数试图获得相同长度length的最长条纹,则您可能只想reduce基本数组。

function longestConsec(arr) {
  return arr
    .reduce((carry, string) => {
      const prev = carry[carry.length - 1];
      const length = string.length;
    
      if (!prev || prev.length !== string.length) {
        carry.push({ length, strings: [string] });
      }
      else {
        prev.strings.push(string);
      }
      
      return carry;
    }, [])
    .sort((one, two) => two.strings.length - one.strings.length)
    .shift().strings;
}


console.log(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"]))

(请注意,我从函数中删除了k参数,因为它似乎没有被使用)

相关问题