簡體   English   中英

為什么我的函數和循環無法訪問我的全局變量?

[英]Why is my function and loop not able to access my global variable?

該節點列表我一直在使用中的功能一直在努力的變量,但它不能在其中,我的工作最新的一個工作。

它給出一個錯誤“未定義卡”。 當我將變量傳遞給函數時,它說它是不可迭代的。

function matchCards() {
    if(hand[0] === hand[1]) {
        addPoint();
    } else if(hand[0] != hand[1]) {
        flipBack();
    }
}
function flipBack (cards) {
    for(card of cards) {
        if(card.firstElementChild.src != "img/cardback.jpeg") {
            for(const id of ids) {
                document.querySelector(`[alt="${id}"]`).src = "img/cardback.jpeg";
                console.log(document.querySelector(`[alt="${id}"]`).src);
                hand = [];
                changePlayer();
            }
        }
    }
}

這是我要使用的全局變量:

const cards = document.getElementsByClassName("card");

這是整個項目的鏈接: https : //codepen.io/ThomasBergman1987/pen/LqrJQM

通過在函數中定義一個具有相同名稱的參數,可以隱藏全局常量的值:

const cards = ...;

function flipBack (cards) {
    // The following print statement will print the 
    // value of the parameter, not the global constant
    console.log(cards); 
}

此外,在其他函數中調用flipBack時,您在不傳遞任何參數的情況下調用了它,這導致參數cards的值不確定。

您可以通過簡單地從函數的參數列表中刪除cards來解決此問題:

function flipBack () {
    // ...
}

至於為什么代碼是說cards是不是可迭代的, cards將是一個HTMLCollection 盡管大多數現代瀏覽器都支持使用for/in對此類對象進行迭代,但是不能保證此功能,並且您無論如何都不應這樣做 比較安全的方法是使用普通的for循環:

function flipBack () {
    for (var i = 0; i < cards.length; i++) {
        var card = cards[i];
        // ...
    }
}

您正在發送卡片作為flipBack()函數的參數,要么刪除它,要么在調用函數flipBack(cards)時再次發送卡片

function matchCards() {
    if(hand[0] === hand[1]) {
        addPoint();
    } else if(hand[0] != hand[1]) {
        flipBack();
    }
}
function flipBack () {
    for(card of cards) {
        if(card.firstElementChild.src != "img/cardback.jpeg") {
            for(const id of ids) {
                document.querySelector(`[alt="${id}"]`).src = "img/cardback.jpeg";
                console.log(document.querySelector(`[alt="${id}"]`).src);
                hand = [];
                changePlayer();
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM