本文介绍了Math.random()在循环中使用时不会给出新的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用Math.random()生成新的随机数时,无论何时,它每次都会为我提供完全相同的答案,但仅限于某些用途.

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;
}

例如,这段代码完全符合我的要求,它将数据集.data [I] [ii]中的每个插槽填充为一个新的随机数.

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.

推荐答案

Math.random()映射到数组时,会为该数组中的每个索引生成一个新的随机数,因此,解决我的问题的方法是在if语句中使用索引.

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
})

这篇关于Math.random()在循环中使用时不会给出新的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 09:15