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

标签 javascript arrays

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

相关文章:

javascript 正则表达式与 g 标志匹配但不与 y 标志匹配

javascript - Angular 和 ngrx : problems during upgrading to version8

javascript - 脚本未运行 jquery .each

Python:ndarray.flatten ('F' 是否有反函数)?

sql - 如何使用 Postgres 轻松地从文本字段中获取首字母

java - 如何在java中比较字符串数组列表值和数组字符串值

c++ - 在 C++ 中通过递归打印数组

javascript - 在 React Native 中调整图像大小

javascript - 从另一个子窗口获得焦点子窗口

php - 在php中从另一个数组创建一个数组