我创建了一个创建一些随机卡的函数,但是当我像init(1)一样调用它时,我的Init函数返回undefined。为什么不起作用?应该是这样的: 我正在调用一个函数,例如init(1) 2. Init创建并随机播放卡片并将其附加到身体
// INIT
{
function init(difficulty) {
switch (difficulty) {
case 1:
createCards(4);
break;
case 2:
createCards(12);
break;
case 0:
createCards(24);
}
}
//FLIP CARD
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 card--reversed";
gameCardBack.className = "card__back";
const img = new Image();
function randImg() {
const uniqueSrc = {}
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));
if (!uniqueSrc[randomSrc]) {
uniqueSrc[randomSrc] = randomSrc;
img.src = "img/" + imgArray[randomSrc] + ".png";
img.alt = imgArray[randomSrc];
gameArray.push(img);
} else {
i--;
}
}
return gameArray;
}
randImg();
gameCardBack.appendChild(img);
gameCards.push(gameCard)
}
return gameCards;
}
const cards = document.querySelectorAll(".card.card--click");
//FETCHING ALL CARDS
for (let i = 0; i < cards.length; i++) {
const card = cards[i];
//ADDING FLIP EFFECT TO EACH CARD
flipCard(card);
};
//FLIP EFFECT FUNCTION
function flipCard(card) {
card.addEventListener("click", function() {
const list = this.classList;
list.contains("card--flip") === true ? list.remove("card--flip") : list.add("card--flip");
});
};
function randomizer(array) {
for (let i = 0; i < array.length; i++) {
const j = Math.floor(Math.random() * (i + 1));
const tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
}
答案 0 :(得分:1)
1)事情是你没有将你的卡贴在身上。所以你可能想在init函数中返回卡片:
function init(difficulty) {
switch (difficulty) {
case 1:
return createCards(4);
break;
case 2:
return createCards(12);
break;
case 0:
return createCards(24);
}
}
然后你可以将init返回的数组附加到body:
init(0).forEach(function(card){
document.body.appendChild(card);
});
2)这也是:
randImg();
没有意义,因为randImg返回一个数组,你可能想要抓住它:
arr=randImg();
3)randImg也不起作用,你需要把
const img=new Image();
进入循环。
4)和
const cards = document.querySelectorAll(".card.card--click");
除非您之前运行上面的代码段,否则将是一个空集合...