制作一个涉及生成随机数的项目,使用 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/