JavaScript generate random numbers without repeating(JavaScript 生成随机数而不重复)
问题描述
我有一些代码,其中包含 x 数量的项目.在这种情况下,视频,我想随机调用一个视频,但是如果当前已经调用的视频与随机数相同,我希望它生成另一个随机数,直到它是唯一的.
I have some code where I have an array of x amount of items. In this case, videos, and I want to randomly call a video, however if the current video already called is the same as the random number I want it to generate another random number until it's unique.
这是我的代码:
var videoLinks = [
['<iframe id="vid" src="https://www.youtube.com/embed/nYm2G4MnSkY?autoplay=1" frameborder="0" allowfullscreen></iframe>'],
['<iframe id="vid" src="https://www.youtube.com/embed/wAgZVLk6J4M?autoplay=1&start=5&end=45" frameborder="0" allowfullscreen></iframe>'],
['<iframe id="vid" src="https://www.youtube.com/embed/ix9wpslKwBE?autoplay=1" frameborder="0" allowfullscreen></iframe>'],
['<iframe id="vid" src="https://www.youtube.com/embed/OJJ-iLsQOPc?autoplay=1&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>'],
['<iframe id="vid" src="https://www.youtube.com/embed/rore790l_sk?autoplay=1&start=12&end=94" frameborder="0" allowfullscreen></iframe>'],
];
var randomNumber = function () {
var getRandomNumber = Math.floor(Math.random() * 5);
var random = videoLinks[getRandomNumber]
document.getElementById("videoWrapper").innerHTML = random[0];
};
randomNumber(); // To call the function on load
推荐答案
用一个变量来检查个数是否相同.
use a variable to check if the number is the same.
类似这样的:(使用 LastNumber 存储 lastNumber)如果它已经被使用,我们会再试一次)
something like this: (using LastNumber to store the lastNumber) if it allready is used we gonna try again)
var videoLinks = [
....
];
var lastNumber = 0;
var randomNumber = function () {
var getRandomNumber = Math.floor(Math.random() * 5);
if(getRandomNumber != lastNumber){
var random = videoLinks[getRandomNumber];
document.getElementById("videoWrapper").innerHTML = random[0];
lastNumber = getRandomNumber;
}else{
randomNumber();
}
};
randomNumber(); // To call the function on load
这篇关于JavaScript 生成随机数而不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 生成随机数而不重复
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01