问题
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