代码之家  ›  专栏  ›  技术社区  ›  Rokas Simkus

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

  •  0
  • Rokas Simkus  · 技术社区  · 7 年前

    我在使用Array.map()方法时出现了一个奇怪的错误。为什么

    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 回复  |  直到 7 年前
        1
  •  2
  •   Code Maniac    7 年前

    当您到达的最后一个索引 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))

    forEach

        2
  •  2
  •   Mamun    7 年前

    为什么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))
        3
  •  0
  •   Mathias W    7 年前


    此外 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))
    
        4
  •  0
  •   adiga    7 年前

    正如其他人已经提到的,当循环到达最后一个元素时,就会出现错误。 strarr[index+1] undefined 你无法访问它的 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 如果循环遇到最后一个元素。

        5
  •  0
  •   Rogier Spieker    7 年前

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

    如果函数作为一个整体试图获得相同长度的刺的最长条纹,您可能只想 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