【问题标题】:Function that is intended to return an array is returning undefined. Console.log(array) within function returns the array旨在返回数组的函数返回未定义。函数内的 Console.log(array) 返回数组
【发布时间】:2019-10-30 03:23:19
【问题描述】:

我正在尝试编写一个函数,该函数接受一个数组并返回一个新数组,其中所有元素都向左移动了 n 个索引。例如:

rotLeft([1,2,3,4],2)
// should return [3,4,1,2]

我编写了一个递归函数,它删除索引 0 处的值并使用 .shift() 和 .push() 将其分配给最后一个索引。

const rotLeft = (array, n) => {
  console.log(array, n); // <-- this prints out expected array
  if (!n) return array; // <-- but this returns undefined! :(
  array.push(array.shift());
  rotLeft(array, n - 1);
};
console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));

为什么每个 console.log(array) 都打印出预期的数组,但函数返回时数组未定义?

【问题讨论】:

  • 需要返回递归结果:return rotLeft(array, n - 1);
  • 因为你没有返回递归得到的值

标签: javascript arrays ecmascript-6


【解决方案1】:

或者您可以使用Array.prototype.slice() 存档

const arr = [1,2,3,4]

const rotLeft = (arr, n) => arr.slice(n).concat(arr.slice(0,n))

const tmp1 = rotLeft(arr, 2)
const tmp2 = rotLeft(arr, 3)
console.log("tmp1", tmp1)
console.log("tmp2", tmp2)

【讨论】:

    【解决方案2】:

    你需要return递归调用。

    const rotLeft = (array, n) => {
      if (!n) return array;
      array.push(array.shift());
      return rotLeft(array, n - 1);
    };
    console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));

    【讨论】:

      【解决方案3】:

      您没有返回旋转数组(对于每个递归调用),您需要另一个 return 用于 rotLeft(array, n - 1):

      const rotLeft = (array, n) => {
        // console.log(array, n);
        if (!n) return array;
        array.push(array.shift());
        return rotLeft(array, n - 1); // <-- return the rotated array (recursively)
      };
      console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));

      甚至更短(使用concat 和三元运算符):

      const rotLeft = (array, n) => {
        return n ? rotLeft(array.concat([array.shift()]), n - 1) : array;
      };
      console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));

      【讨论】:

        【解决方案4】:

        试试下面的代码。您没有从函数返回结果。我刚刚添加了return语句

        const rotLeft = (array, n) => {
          //console.log(array, n); // <-- this prints out expected array
          if (!n) return array; // <-- but this returns undefined! :(
          array.push(array.shift());
          return rotLeft(array, n - 1);
        };
        

        用法: rotLeft([1,2,3,4],2)

        输出

        【讨论】:

        • 没问题 :-) 这就是为什么我们有这个在线社区来互相帮助的原因。快乐编码:-)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-14
        • 1970-01-01
        • 1970-01-01
        • 2021-05-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多