创建随机Ints的JavaScript数组

ben*_*ope 1 javascript underscore.js

在Python中,如果我想要一个特定大小的随机数组,我会:

random_array = numpy.random.randint(20, size=10)
Run Code Online (Sandbox Code Playgroud)

在Javascript中,我无法找到一个很好的单行方式来做到这一点.我尝试使用UnderscoreJS:

random_array = _.sample(_.range(20), 10);
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用Javascript 1.7数组理解和UnderscoreJS:

random_array = [Math.floor(Math.random() * 20) for (x of _.range(10))];
Run Code Online (Sandbox Code Playgroud)

第一种方法只创建唯一值,第二种方式似乎根本不起作用.有任何想法吗?做这个的最好方式是什么?

Fel*_*ing 5

貌似_.times_.random将是有益的:

var random_array = _.times(10, _.random.bind(_, 0, 19));
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个小辅助函数_.random:

function randomIntFactory(max) {
    // _.random's max value is *inclusive* (unlike the Python version)
    // so we subtract one
    return _.random.bind(_, 0, max - 1);
}

var random_array = _.times(10, randomIntFactory(20));
Run Code Online (Sandbox Code Playgroud)

注意:.bind您也可以使用下划线代替本机_.bind.