Math.random() when used in loop will not give new number

跟風遠走 提交于 2020-01-02 23:00:12

问题


When I try to generate a new random number using Math.random() it gives me the EXACT same answer every single time no matter what, but only in certain uses.

By the way I have a custom random function:

function random(min, max) {
 return Math.random() * (max - min + 1) + min;
}

For example, this code does exactly what I want it to, it fills each slot in dataset.data[I][ii] to a NEW random number.

dataset.data.forEach((point, index) => {
 //fill dataset with random numbers
 dataset.data[index] = point.map(() =>
    Math.round(random(0, screen.get().width))
 );
});

However, when I use this code, It fills the array with the exact same random number each time.

dataset.data.forEach((point, index) => {
 //fill dataset with random numbers
 dataset.data[index][0] = Math.round(random(0, screen.get().width));
 dataset.data[index][1] = Math.round(random(0, screen.get().height));
});

I keep encountering this issue and I do not understand it, I do understand that there are at times large quantities of the same number, but no matter what I do, in certain circumstances like these, only one way of writing it works, which is not helpful.


回答1:


Math.random(), when mapped to an array, generates a new random number for each index in that array, so a workaround to the problem of mine is using the index in an if statement.

arr = new Array(2).fill([]);
arr.forEach((point, index) => {
    arr[index] = point.map((array, index) => i===theSpotInYourArray?returnthis:orreturnthis
})


来源:https://stackoverflow.com/questions/59539987/math-random-when-used-in-loop-will-not-give-new-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!