我创建了一组随机生成的图像。并且随机生成的图像中的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>
答案 0 :(得分:0)
您可以使用.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>