这个setTimeout函数对我来说没有意义

时间:2019-12-01 22:09:42

标签: javascript if-statement settimeout

这是我尝试构建的简单比赛纸牌游戏。在第一个if语句中,我正在检查数组中的网址是否不匹配。如果没有,我将重新显示卡片图像的背面。但是,在else部分中,我想从板上删除两张卡,但是只删除最后单击的卡,而不是第一张和最后一张卡。我想删除比较的两个,如果它们具有相同的URL。谢谢

const card = document.querySelector(".main-board");
var arr = [];

card.addEventListener("click", function(e){
    e.target.src = randomOrder(images);
    arr.push(e.target.src);




//This if statement is what's giving me trouble
    if(arr[0] !== arr[1]) {
        setTimeout(function(){
            e.target.src = "https://i.pinimg.com/originals/c1/59/b4/c159b4738dae9c9d8d6417228024de8d.jpg";
        }, 2000);
    } else {
        setTimeout(function(){
            e.target.style.display = "none";
        }, 2000);
    }
    if(arr.length > 1) {
        arr = [];
    }
});

function randomOrder(images) {
    return images[Math.floor(Math.random()*images.length)];
}

const images = [
    "https://images.unsplash.com/photo-1541233349642-6e425fe6190e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
    "https://images.wallpaperscraft.com/image/butterflies_mushrooms_forest_130001_1280x1280.jpg",
    "https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-260nw-1048185397.jpg",
    "https://i2.wp.com/buzzonearth.com/wp-content/uploads/2018/12/pexels-photo-814499.jpeg?resize=500%2C333&ssl=1",
    "https://images.unsplash.com/photo-1542725577-5240e614e436?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80"
]

1 个答案:

答案 0 :(得分:0)

如果将目标本身而不是目标src推入数组怎么办:

card.addEventListener("click", function(e){
    e.target.src = randomOrder(images);
    arr.push(e.target);
if(arr.length === 1)  return;   //there shouldn't be comparison with one array element only
//This if statement is what's giving me trouble
    if(arr[0].src !== arr[1].src) {
        setTimeout(function(){
            arr[0].src = "https://i.pinimg.com/originals/c1/59/b4/c159b4738dae9c9d8d6417228024de8d.jpg";
            arr[1].src = "https://i.pinimg.com/originals/c1/59/b4/c159b4738dae9c9d8d6417228024de8d.jpg";
        }, 2000);
    } else {
        setTimeout(function(){
          arr[0].style.display = "none";
          arr[1].style.display = "none";
        }, 2000);
    }
    if(arr.length > 1) {
        arr = [];
    }
});