检查如果值在数组javascript中存在两次

时间:2017-04-16 14:15:55

标签: javascript arrays

所以基本上我想创建一个需要一些隐藏图像的记忆卡游戏。我写了一个函数,但它返回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);

1 个答案:

答案 0 :(得分:1)

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;
};

似乎你的代码有一些bug。已修复它,现在可以正常工作。