为什么不能使用_.map(new Array(n),Math.random)创建随机数组? [英] Why can't I create a random array using _.map(new Array(n), Math.random)?

查看:44
本文介绍了为什么不能使用_.map(new Array(n),Math.random)创建随机数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个0到1之间的随机数数组,所以我尝试了:

I want to make an array of random numbers between 0 and 1, so I tried:

var randList = _.map(new Array(5), Math.random);

但是我没有得到我期望的随机元素列表,而是得到了:

But instead of getting the list of random elements that I expected, I got:

console.log(JSON.stringify(randList));
"[null,null,null,null,null]"

为什么我会得到一个空数组而不是随机数?

Why did I get an Array of null instead of random numbers?

推荐答案

Array(length)构造函数创建一个稀疏数组.即,将数组的长度设置为指定的参数,但不填充数组的元素.结果, map 方法不会遍历这些未填充"的元素.例如,以下代码片段在控制台上不产生任何输出:

The Array(length) constructor creates a sparse array. That is, the length of the array is set to the specified parameter, but the elements of the array are not populated. As a result, the map method does not iterate over these 'unpopulated' elements. For example, the following snippet does not produce any output on the console:

var arr = new Array(5);
for(var x in arr) console.log(x);

但是请注意,像这样初始化数组将产生预期的结果:

Note, however, that initializing the array like this will produce the expected result:

console.log(_.map([0,0,0,0,0], Math.random));

当然,这不会扩展.如果您希望数组中的元素数是可变的,我建议您使用 times 方法:

Of course, this doesn't scale. If you want the number of elements in the array to be variable, I would recommend you use the times method instead:

var randList = _(5).times(Math.random);

var randList = _.times(5, Math.random);

这篇关于为什么不能使用_.map(new Array(n),Math.random)创建随机数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆