在 JavaScript 中使用随机数创建长度为 n 的数组 [英] Creating array of length n with random numbers in JavaScript

查看:17
本文介绍了在 JavaScript 中使用随机数创建长度为 n 的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 this answer 创建指定长度的数组,我执行了以下操作以获得相应的结果,但是填充随机数,而不是零.

Following up on this answer for creating an array of specified length, I executed the below to get a corresponding result but filled with random numbers, instead of zeros.

var randoms = Array(4).fill(Math.floor(Math.random() * 9));

好吧,从数学上讲它是随机的,好吧.但我希望随机性在数组中可见,而不仅仅是在运行之间,当然.愚蠢的电脑……别按我说的做.做我想做的!

Well, mathematically speaking it's random, all right. But I'd like the randomness to be visible within the array and not only between runs, of course. Stupid computer... Don't do what I say. Do what I want!

我可以迭代并将其放入我的随机(和变化)值.但出于纯粹的好奇,我想知道是否有可能通过单线获得正确的结果,就像上面那样,MatLab 风格.我需要调用 eval(function()...) 吗?我听说过很多关于 eval 的坏事...

I can iterate and put it my random (and varying) values. But I wonder, of pure curiosity, if it's possible to get the right result with a one-liner, like above, MatLab-style. Do I need to call eval(function()...)? I've heard a lot of bad things about eval...

注意上面的代码是这样的:

Note that the above produces code like this:

[7, 7, 7, 7]
[3, 3, 3, 3]

[7, 7, 7, 7]
[3, 3, 3, 3]

等等.虽然我想要类似的东西

etc. while I want something like

[1, 2, 3, 4]
[4, 3, 8, 4]

[1, 2, 3, 4]
[4, 3, 8, 4]

推荐答案

我想知道是否有可能用单线获得正确的结果...

I wonder if it's possible to get the right result with a one-liner...

var randoms = [...Array(4)].map(() => Math.floor(Math.random() * 9));

document.body.innerText = randoms;

这篇关于在 JavaScript 中使用随机数创建长度为 n 的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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