gpt4 book ai didi

Javascript:存储最后生成的随机数

转载 作者:行者123 更新时间:2023-11-30 11:29:53 25 4
gpt4 key购买 nike

制作一个涉及生成随机数的项目,使用 Math.random() 很容易。每 n 秒将生成一个新数字,我希望能够显示 5 个最近的数字。

我能想到的最好办法是创建一个包含所有生成数字的数组,推送新数字,然后获取 5 个最新索引。

有没有更好的方法只存储最近的 5 个数字,因为将生成数千个这样的数字?

最佳答案

The best I could come up with is creating an array with all the generated numbers, pushing new ones, and then getting the 5 most recent indexes.

不只是推,而是做 shift并插入

var randomArr = [];
function addRandom()
{
//var newNum = randomNumber();

if ( randomArr.length >= 5 )
{
randomArr.shift();
}
randomArr.push( newNum );
}

现在不需要拼接了,直接拿randomArr数组就可以了。

关于Javascript:存储最后生成的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46643681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com