[英]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.