lodash/underscore.js函数来创建由x的n个副本组成的数组

lodash / underscore.js function to create array consisting of n copies of x

本文关键字:副本 数组 underscore js 函数 创建 lodash      更新时间:2023-09-26

我怀疑我问这个问题的原因是我的词汇表中缺少一个更好的术语来描述我要查找的函数,因此我无法在谷歌和lodash API文档中找到它

underscorelodash是否提供了一个专用函数,通过简单地将x的(返回)值推到空数组n次来生成数组,其中x是值或生成器函数?

我可以想到这样一个函数的许多用例,尽管使用简单的for循环可以很容易地复制该功能,但underscorelodash等实用程序库提供的函数通常是这样的,它们的目的通常是提供最佳实现

事实证明_.times几乎提供了我想要的功能;如API官方文件所述:

_.times(n, [iteratee=_.identity], [thisArg]) 
// Invokes the iteratee function n times, returning an array of the results of each invocation. The iteratee is bound to thisArg and invoked with one argument; (index).

不过,这显然不允许我传递静态值。

不是一个专用函数,但也许这就足够了?:

.map(.range(n),x)

编辑:正如Pointy所建议的,如果x是生成器,_.times()将执行您所描述的操作:

_.times(n, x)

如果_.times不是函数,它将忽略x,因此您可能需要使用一个mixin:

_.mixin({ 
    generate: function (length, x) { 
        return _.times(length, _.isFunction(x) ? x : _.constant(x));
    }
});