嗨,我正在做一个显示随机图像的任务。我的代码显示随机图像,但实际上我想显示无重复的随机图像。如何做到这一点。帮我。预先感谢。
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
var imagesused = [];
$('.advertisement div').each(function() {
var rand = Math.floor(Math.random() * images.length);
$(this).append('<img src="' + images[rand] + '"/>');
if (imagesused.indexOf(images[rand]) != -1) images.splice(rand, 1);
else imagesused.push(images[rand]);
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
答案 0 :(得分:1)
复制原始数组。在添加随机图像后,将其从数组副本中删除。从数组中删除图像时,无需创建imagesUsed
。
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
//making copy of original array.
var tempImgs = images.slice(0)
$('.advertisement div').each(function() {
var rand = Math.floor(Math.random() * tempImgs.length);
$(this).append('<img src="' + tempImgs[rand] + '"/>');
tempImgs.splice(rand, 1);
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
答案 1 :(得分:0)
我的方法是这样的,无论您的数组大小如何,这种方式都可以将它们随机化
首先创建一种将其洗牌的方法
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
然后在循环数组之前使用它
images = shuffle(images);
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
images = shuffle(images);
var imagesused = [];
$('.advertisement div').each(function(x) {
$(this).append('<img src="' + images[x] + '"/>');
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>