const cardSet = ['fa fa-diamond','fa fa-diamond','fa fa fa-paper-plane-
o','fa fa-paper-plane-o','fafa-anchor','fa fa-anchor','fa fa-bolt','fa fa-
bolt','fa fa-cube','fa fa-cube','fa fa-leaf','fa fa-leaf','fa fa-
bicycle','fa fa-bicycle','fa fa-bomb','fa fa-bomb'];
let cardsOpen=[];
let cardsflipped = 0;
const theDeck = document.querySelector('deck');
window.onload=function(){
shuffle(cardSet);
for(let i; i<=cardSet.length;i++){
let cards= document.createElement('li');
cards.innerHTML='<i class="'+ cardSet[i] +'"></i>';
cards.classList.add('card');
theDeck.appendChild(cards);
你好这是一款记忆游戏的javascript。 这段代码应该洗牌所有的牌并在DOM上创建元素,但由于某种原因它不起作用。 有人能帮助我理解为什么吗?
答案 0 :(得分:0)
假设shuffle
方法正常工作,我可以在代码中发现两个错误:
const cardSet = ['fa fa-diamond', 'fa fa-diamond', 'fa fa fa-paper-plane-o', 'fa fa-paper-plane-o', 'fafa-anchor', 'fa fa-anchor', 'fa fa-bolt', 'fa fa-bolt', 'fa fa-cube', 'fa fa-cube', 'fa fa-leaf', 'fa fa-leaf', 'fa fa-bicycle', 'fa fa-bicycle', 'fa fa-bomb', 'fa fa-bomb'];
let cardsOpen = [];
let cardsflipped = 0;
// you probably meant #deck, unless you have a nonstandard <deck />
// element in your code. querySelector accepts a CSS-style selector,
// which is why it is called that.
const theDeck = document.querySelector('#deck');
window.onload = function() {
shuffle(cardSet);
// use let, and you have to assign i to 0
// otherwise it will be undefined and undefined + 1 = NaN
// and NaN + 1 = NaN so this loop will never terminate
for (let i = 0; i <= cardSet.length; i++) {
let cards = document.createElement('li');
cards.innerHTML = '<i class="' + cardSet[i] + '"></i>';
cards.classList.add('card');
theDeck.appendChild(cards);
}
}