代码之家  ›  专栏  ›  技术社区  ›  Chris Marshall

递归数组问题

  •  1
  • Chris Marshall  · 技术社区  · 6 年前

    对于递归函数来说,这是一个没有意义的问题,不能很快理解为什么下面的代码可以工作,但是当试图在一行中完成所有这些时,在js中却没有反应?

    Works:
    generateDummyData(num, sentences) {
        sentences.push(randomSentence());
        return num === 1 ? sentences : this.generateDummyData(num-1, sentences);
    }
    
    Doesnt Work:
    generateDummyData(num, sentences) {
        return num === 1 ? sentences : this.generateDummyData(num-1, sentences.push(randomSentence()));
    }
    

    任何帮助解释或说明一个更好的方式来做我的尝试将不胜感激。期待评论。

    更新

    一个很好的解决方法是创建一个新数组,并将旧数据传播到新数组中。不知道性能和内存是否会受到这样的影响,但它确实有效。

    generateDummyData(num, sentences) {
        return num === 1 ? sentences : this.generateDummyData(num-1, [...sentences, randomSentence()]));
    }
    
    4 回复  |  直到 6 年前
        1
  •  4
  •   kockburn    6 年前

    sentences.push(randomSentence())

    push()方法将一个或多个元素添加到数组的末尾,然后 返回数组的新长度。

    Source: MDN push doc

    var test = ["a", "b", "c"];
    
    console.log(test.push("d"));
        2
  •  1
  •   Andy Gaskell    6 年前

    push 在你的第二个例子中。这个 result of push is the length of the array ,而不是数组本身。这样的方法应该有用:

    return num === 1 ? 
        sentences : 
        this.generateDummyData(
           num - 1, sentences.push(randomSentence()) && sentences
        );
    
        3
  •  0
  •   Beri    6 年前

    根据 Array.prototype.push() ,它返回

    打电话。

    sequences 你的下一个方法调用,但序列长度。

    这就是为什么这两种方法不相等。

        4
  •  0
  •   Shubham Khatri    6 年前

    Push在向数组中添加元素后返回数组的大小,因此当您在向函数传递数据时使用它时,它会在Push value之后传递返回值,而不是数组值。你应该改用concat

    generateDummyData(num, sentences) {
        return num === 1 ? sentences : this.generateDummyData(num-1, sentences.concat([randomSentence()]));
    }