我在我的HTML体设置2个图像标记被从阵列显示2个随机化图像。其次,我已经确保了2个显示的随机图像将无法通过代码行重演var Brand = BrandNameArray.splice(random_BrandIndex, 1)[0];
然而,当我运行的代码,我已经注意到了,在HTML正文第二图像标签的第二图像显示错误的图像。它显示的图像索引为+1。
含义:
我有一个array_Image = [A,B,C,d,E]和我的控制台日志内,则指出,随机图像返回[0,3]的2张图像,因此正确地说,它应该在我的html body的图像标签中显示图像[A,D]。但是,显示的图像是[A,E]。以下行为发生了很多次,即使它不一致。
请问我可以得到一些帮助。谢谢。
我附上以下代码供您细读。
时所显示的用户点击的随机生成的图像的onclick="selectBrand('2');
下面的代码被调用时,将显示一个弹出图像,这也是从被附加到Brand_list.push(random_BrandIndex);
另一个阵列,这取决于正被推向临时存储在图像上阵列 - >var Brand_List=[];
//Brand Offers
var Brand_list = [];
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"];
//Randomised Brand Offer
//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];
console.log("Brand:" + Brand);
var Brand = BrandNameArray.splice(random_BrandIndex, 1)[0];
Brand_list.push(random_BrandIndex);
$(img).attr('src', Brand).show();
});
console.log("Brand_list:" + "[" + Brand_list + "]");
<div id="MainBackground" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; z-index=8; top:0px; left:0px; margin:auto;">
<!--Div to show my 2 randomised images-->
<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>
</div>
OK,“().splice”为什么我已经使我们的原因是为了防止这种'[0,0]'所以它永远不会有重复的发生'var Brand_List'的商店阵列中的图像。那么我想问一下,拼接不是一种确保显示单一图像的好方法吗?在[0,0]事件中我没有发现,即使我拼接了随机数组 – Luke
看到,当你拼接你的图像数组时,你正在从数组中删除图像而不是索引!指数转变。 –
我也观察到一些其他行为,如果我要输入.splice(arrayName,0); ,仍会显示重复的图像。那么这是否意味着,拼接后,我将不得不将元素放回数组中? – Luke