gpt4 book ai didi

javascript - 如何找到不在数组中的随机数?想要遍历随机数直到找到一个

转载 作者:行者123 更新时间:2023-11-30 17:37:14 24 4
gpt4 key购买 nike

我有一个包含 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. */
}

最佳答案

创建数组的副本,随机排序,并在创建时从数组中删除它们。无需继续生成随机数或跟踪使用了什么。

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();

关于javascript - 如何找到不在数组中的随机数?想要遍历随机数直到找到一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21786193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com