gpt4 book ai didi

javascript - 检查数组javascript中值是否存在两次

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:28 25 4
gpt4 key购买 nike

所以基本上我想创建一个需要一些隐藏图像对的内存卡游戏。我已经编写了一个函数,但它返回 NaN 而且我真的不知道如何检查数组中的某些 src 是否已经存在两次。

  function createCards(ammount) {
const gameCards = document.createElement("div") * ammount;
for (let i = 0; gameCards.length - 1; i++) {
gameCards[i].className = "card.card--click";
const gameCardFront = document.createElement("div");
const gameCardBack = document.createElement("div");
gameCards[i].appendChild(gameCardFront);
gameCards[i].appendChild(gameCardBack);
gameCardFront.className = "card__front";
gameCardBack.className = "card__back";
function randImg() {
const img = new Image();
const imgArray = ["ball", "car", "fork", "spoon", "sun"];
const gameArray = [];
for (let i = 0; i < ammount * 2 + 1; i++) {
const randomSrc = Math.floor(Math.random() * (imgArray.length));
img.src = "img/" + imgArray[randomSrc] + ".png";
img.alt = imgArray[randomSrc];
gameArray.push(img);
}
return gameArray;
}
randImg();
gameCardBack.appendChild(img);
}
return gameCards;
};
createCards(8);

最佳答案

function createCards(ammount) {
const gameCards = []
for (let i = 0; i < ammount; i++) {
const gameCard = document.createElement("div");
gameCard.className = "card.card--click";
const gameCardFront = document.createElement("div");
const gameCardBack = document.createElement("div");
gameCard.appendChild(gameCardFront);
gameCard.appendChild(gameCardBack);
gameCardFront.className = "card__front";
gameCardBack.className = "card__back";
function randImg() {
const uniqueSrc = {};
const imgArray = ["ball", "car", "fork", "spoon", "sun"];
const images = document.createElement("div");
for (let i = 0; i < ammount * 2 + 1; i++) {
const randomSrc = Math.floor(Math.random() * (imgArray.length));
const img = new Image();
if (!uniqueSrc[randomSrc]) {
uniqueSrc[randomSrc] = randomSrc;
img.src = "img/" + imgArray[randomSrc] + ".png";
img.alt = imgArray[randomSrc];
images.appendChild(img);
} else {
i--;
}
}
return images;
}
const images = randImg();
gameCardBack.appendChild(images);
gameCards.push(gameCard)
}
return gameCards;
};

您的代码似乎有一些错误。已修复,现在可以正常工作了。

关于javascript - 检查数组javascript中值是否存在两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43438158/

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