“重复n次”的成语?

新手上路,请多包涵

这是在 JS 中生成 3 个随机数数组的一种有点浪费且不切实际的方法:

 [1, 1, 1].map(Math.random) // Outputs: [0.63244645928, 0.59692098067, 0.73627558014]

使用虚拟数组(例如 [1, 1, 1] ),只是为了可以调用 map 在它上面,对于足够大的 n - 既浪费(内存)又不切实际.

人们想要什么,就像一个假设:

 repeat(3, Math.random) // Outputs: [0.214259553965, 0.002260502324, 0.452618881464]

使用 vanilla JavaScript 我们最接近的是什么?

我知道像 Underscore 这样的库,但我尽量避免使用这里的库。

我看了 Repeat a string a number of times 的答案,但一般情况下不适用。例如:

 Array(3).map(Math.random) // Outputs: [undefined, undefined, undefined]
Array(4).join(Math.random()) // Outputs a concatenation of a repeated number
Array(3).fill(Math.random()) // Fills with the same number

其他几个答案建议修改内置类;我认为这是完全不能接受的做法。

原文由 kjo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 277
2 个回答

Underscore.js 有一个 times 函数,可以完全满足您的需求:

 _.times(3, Math.random)

如果您不想使用 Underscore,您可以编写自己的 times 函数(从 Underscore 源代码复制并稍微简化):

 times = function(n, iterator) {
  var accum = Array(Math.max(0, n));
  for (var i = 0; i < n; i++) accum[i] = iterator.call();
  return accum;
};

原文由 David Brown 发布,翻译遵循 CC BY-SA 3.0 许可协议

可以 使用 Array.prototype.map 来完成,但数组不能为空。先 一下:

 console.log(
    Array(3).fill().map(Math.random)
);

解释:

new Array(3) 构造函数创建 一个稀疏数组(或 “多孔”数组,V8 团队称它们为),其中 有三个孔,长度为三。这意味着它等同于 [,,,] ,创建 [<empty>, <empty>, <empty>,] (注意 JavaScript 的 尾随逗号)。请注意,一个空槽,即一个孔与 undefined 分配的值不同。 undefined 是一个实际值,而 <empty> 只是数组中的一个空隙。

Array.prototype.map数组中的每个元素调用一次。但是,因为空数组没有分配值,所以根本不会调用回调。例如, [1,,2].map(v=>v*2) 会给出 [2,,4] ;中间槽被跳过,因为它在那里有一个间隙。

输入 Array.prototype.fill(value, start?, end?) :只有一个参数,它用指定的值填充数组中的每个槽。从技术上讲,第一个参数不是可选的,但通过省略它, undefined 用作值。这没关系,因为无论如何都没有使用该值。这样 Array(3).fill() 给我们 [undefined, undefined, undefined]

现在数组中有值,它可以被映射,如上所示。


您还可以 spread 空的 array undefined 在映射之前转换为 --- 的值:

 console.log(
    [...Array(3)].map(Math.random)
);

解释:

ECMAScript2015 或更新版本中引入的数组运算符将 数组中的空洞视为 undefinedArray.prototype.map 是在 ES5 中引入的( 即 ES2015 之前的版本),令人困惑的是,数组中的空洞将被跳过,这在 JS 数组函数中造成了一些不一致,具体取决于它们发布的 ECMAScript 版本在。

扩展运算符 ... 是在 ES2015 中引入的,因此根据规范,它将给定数组中的任何空洞转换为 undefined 的值。换句话说, [...Array(3)] 给了我们 [undefined, undefined, undefined] ,就像 Array(3).fill() 上面那样。


有时您可能需要按顺序播种。正如 Kevin Danikowski 所指出的, Array.prototype.map 为您提供开箱即用的功能,因为第二个参数是当前密钥:

 const Fibonacci = n => Math.round(((5**.5 + 1) / 2)**n / 5**.5);

console.log(
    Array(10).fill().map((_, i) => Fibonacci(++i))
);

原文由 Okku 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题