js随机数重复生成的问题
在使用math.random()函数生成随机数时,有时会出现随机数重复的问题。例如:
const arr = []; for (let i = 0; i < 2; i++) { const el = math.random(); const practical = math.random(); arr.push({ el, practical }); }
在这种情况下,el.expect和practical的值将相同。为了解决这个问题,可以在每次生成随机数之前更新随机种子,确保每次生成不同的数字。一种简单的方法是在循环内部使用math.random()函数:
const arr = []; for (let i = 0; i < 2; i++) { const el = Math.random(); Math.random(); const practical = Math.random(); arr.push({ el, practical }); }
这将确保每次生成不同的随机数。