我有一个包含10张图片的文件夹(img-1.jpg,img-2.jpg,...)。我目前在一个网站上有6个图像,我试图用一个尚未在页面上显示的不同图像随机交换出6个图像中的一个。
我有一个包含所有图像的数组(fullList),然后生成当前显示的图像数组(currentList)。
我遇到问题的是循环遍历currentList数组,直到找到当前不在currentList数组中的随机生成的项。然后我将从页面中选择一个随机图像并更改图像。
我现在拥有的:
function sawpHeadshots() {
var fullList = [1,2,3,4,5,6,7,8,9,10];
var currentList = [];
$('#headshots li').each(function() {
currentList.push(parseInt($(this).css('background-image').replace(/\D+/, '')));
});
function generateRandom() {
return fullList[Math.floor(Math.random() * fullList.length)];
}
var rand = generateRandom();
/* not sure how to proceed at this point. */
}
答案 0 :(得分:2)
创建数组的副本,对其进行随机排序,并在创建数组时将其从数组中删除。无需继续生成随机数或跟踪使用的内容。
var fullList = [1,2,3,4,5,6,7,8,9,10];
var random = fullList.slice(0).sort(function() {
return .5 - Math.random();
});
//get value with pop()
var current = random.pop();