我一直在使用作为函数变量的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");
您通过在函数中使用相同名称定义参数来隐藏全局常量的值:
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];
// ...
}
}
你发送卡片作为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();
}
}
}
}