为什么我的函数和循环无法访问我的全局变量?

问题描述 投票:-1回答:2

我一直在使用作为函数变量的NodeList一直在工作,但它不能用于我正在工作的最新版本。

它给出了“卡未定义”的错误。当我将变量传递给函数时,它表示它不可迭代。

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

javascript html dom
2个回答
4
投票

您通过在函数中使用相同名称定义参数来隐藏全局常量的值:

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迭代这种对象,但这个功能并不能保证,而且you shouldn't be doing that anyway。更安全的方法是使用正常for循环:

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

0
投票

你发送卡片作为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();
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.