随机生成的图像仍然显示重复
Randomised Generated Image is still showing duplicate
我创建了一个随机生成的图像数组。并且随机生成的图像中的2个将被显示在图像标签中。然而,当前面临的问题是,在图像标签中显示的2个随机图像可以是相同的图像。
我如何能够防止2个相同的随机生成的图像显示。除了使用.splice(parameter,1);
之外,还有其他方法吗???
var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/B.png", "lib/img/Brands/C.png", "lib/img/Brands/D.png", "lib/img/Brands/E.png"];
var Brand_list = [];
//Auto populate into brand container once randomised
$('#BrandWinlist > img').each(function(i, img) {
random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
console.log("random_BrandIndex:" + random_BrandIndex);
//Assign Variable to generate random Brands
var Brand = BrandNameArray[random_BrandIndex];
//BrandNameArray.splice(random_BrandIndex,1);
Brand_list.push(random_BrandIndex);
$(img).attr('src', Brand).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="GameWinBrand_Container">
<div id="BrandWinlist" class="GameWinBrand_innerScroll">
<img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
<img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
</div>
</div>
您可以使用.slice()
创建原始数组的副本,.splice(random_BrandIndex, 1)
从副本中删除项目
var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/B.png", "lib/img/Brands/C.png", "lib/img/Brands/D.png", "lib/img/Brands/E.png"];
var Brand_list = [];
var copy = BrandNameArray.slice(0);
//Auto populate into brand container once randomised
$('#BrandWinlist > img').each(function(i, img) {
random_BrandIndex = Math.floor(Math.random() * copy.length);
console.log("random_BrandIndex:" + random_BrandIndex);
//Assign Variable to generate random Brands
var Brand = copy.splice(random_BrandIndex, 1)[0];
console.log(Brand);
//BrandNameArray.splice(random_BrandIndex,1);
Brand_list.push(random_BrandIndex);
$(img).attr('src', Brand).show();
});
console.log(copy)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="GameWinBrand_Container">
<div id="BrandWinlist" class="GameWinBrand_innerScroll">
<img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
<img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
</div>
</div>
相关文章:
- 使用JSP从服务器检索和显示图像
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 使用FormData上传AJAX图像;t在服务器端显示图像
- 选择文件后显示图像
- Chrome(webkit?)无法在幻灯片中正确显示图像
- 如何使用javascript显示图像
- 使用JS按顺序显示图像,而不是随机显示
- 使用服务器上的HTML/js在网页上显示图像
- 我想在选择输入文件上显示图像
- Javascript:单击单选按钮时显示图像
- 如何将JSON结果设置为'src'共'img'以在ASP.NET MVC4中显示图像
- 无法在cakepp布局中显示图像
- 页面加载后通过javascript显示图像
- 将图像文件存储在猫鼬模式中的二进制数据中,并以html形式显示图像
- 使用AngularJs数据绑定的三元运算符显示图像
- 加载时画布上未显示图像
- 运行POST时显示图像
- NodeJS上没有显示图像
- 从Javascript在表中显示图像
- 如何在MVC5中运行时在HTML5 Canvas中显示图像