Kar*_*gar 17 javascript arrays
我试图使用map生成一些随机数据.令我惊讶的是,我无法弄清楚为什么这段代码不起作用.
请考虑以下代码段,它按预期工作:
const empty = [undefined, undefined];
const rand = empty.map(item => Math.random());
Output: [0.4774752874308936, 0.8482276976659398]
Run Code Online (Sandbox Code Playgroud)
我试图简化一下并执行以下操作
const rand = Array(2).map(item => Math.random())
Output: [undefined × 2]
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样.显然,由Array(n)和[]生成的两个数组都是典型的数组,并且具有所有原型方法.
Array(2) instanceof Array
true
[undefined, undefined] instanceof Array
true
Array.isArray(Array(2))
true
Array.isArray([undefined, undefined])
true
Run Code Online (Sandbox Code Playgroud)
有人能指出我在哪里错了吗?
T.J*_*der 21
Array(2)给你一个长度为的空数组2.JavaScript数组本质上是稀疏的(它们可能有漏洞,因为它们根本不是真正的数组),这就是Array(2)给你的东西.它看起来像这样:
+??????????????+ | (array) | +??????????????+ | length: 2 | +??????????????+
而你的[undefined, undefined]数组看起来像这样:
+??????????????+ | (array) | +??????????????+ | length: 2 | | 0: undefined | | 1: undefined | +??????????????+
map,forEach和大多数(但不是全部)相关方法Array.prototype仅循环通过稀疏数组的实际条目.由于返回的数组Array(2)没有任何实际条目,因此永远不会调用您的回调.
添加了ES2015 Array#fill(并且可以填充),您可以使用它来填充数组:
const rand = Array(2).fill().map(Math.random)
console.log(rand);Run Code Online (Sandbox Code Playgroud)
(注意,由于Me.Name 指出我们不需要item => Math.random,我们可以Math.random直接调用;它不使用this或其参数(spec).)
还有这个技巧用于创建带有s 的填充数组undefined:
const empty = [...Array(2)]:
Run Code Online (Sandbox Code Playgroud)
如果你不想要的话,你可以这样申请fill:
const rand = [...Array(2)].map(Math.random);
console.log(rand);Run Code Online (Sandbox Code Playgroud)
Array.from({length: 2}, Math.random);
Run Code Online (Sandbox Code Playgroud)
例如:
const rand = Array.from({length: 2}, Math.random);
console.log(rand);Run Code Online (Sandbox Code Playgroud)
Array.apply(null, {length: 2}).map(Math.random);
Run Code Online (Sandbox Code Playgroud)
var rand = Array.apply(null, {length: 2}).map(Math.random);
console.log(rand);Run Code Online (Sandbox Code Playgroud)
¹ (这是我贫血小博客上的帖子)
| 归档时间: |
|
| 查看次数: |
3462 次 |
| 最近记录: |