简体   繁体   English

在JavaScript中生成具有随机数的数组

[英]Generate arrays with random numbers in javascript

I need to create an array (observations) which contains arrays of eight numbers (named observation). 我需要创建一个数组(观测值),其中包含八个数字的数组(称为观测值)。 These numbers should be in range between 0 and 9. 这些数字应介​​于0到9之间。

let observations = [];
let observation = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
    for (let j = 0; j < 8; j++) {
        observation[j] = Math.floor(Math.random() * (max - min + 1)) + min;
    }
    observations.push(observation);
}

Problem: The numbers are pseudo random and I get the same result 20 000 times. 问题:数字是伪随机数,我得到2万次相同的结果。

Is there a possibility to fix this issue in JavaScript? 是否有可能在JavaScript中解决此问题?

You're reusing the same observation array each time, but simply overwriting it in the inner loop. 您每次都重复使用相同的observation数组,而只是在内部循环中覆盖它。 So all the references to it contain the results from the last iteration. 因此,对其的所有引用都包含上次迭代的结果。

You need to create a new observation array each time through the outer loop. 您每次需要通过外循环创建一个新的observation数组。

let observations = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
    let observation = [];
    for (let j = 0; j < 8; j++) {
        observation.push(Math.floor(Math.random() * (max - min + 1)) + min);
    }
    observations.push(observation);
}

You could move the empty array inside of the first level, because you keep the same object reference. 您可以将空数组移到第一级内部,因为您保留了相同的对象引用。

let observations = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
    let observation = [];
    for (let j = 0; j < 8; j++) {
        observation[j] = Math.floor(Math.random() * (max - min + 1)) + min;
    }
    observations.push(observation);
}
Math.seed = function(s) {
    return function() {
        s = Math.sin(s) * 10000; return s - Math.floor(s);
    };
};

let observations = [];
let observation = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
        var d = new Date();
        var n = d.getMilliseconds();
    for (let j = 0; j < 8; j++) {
        observation[j] = Math.floor(Math.seed(i+j+n)() * (max - min + 1)) + min;
    }
    observations.push(observation);
    observation = [];
}

JSON.stringify(observations);

A functional solution: 功能解决方案:

const observations = Array.from({length: 20000}, () => 
  Array.from({length: 10}, () => (Math.random() * 10 | 0)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM