我希望能够单击下面的按钮并洗牌我的牌组中的牌。
到目前为止,我已经创建了一个事件监听器,当单击该事件监听器时,它会调用带有数组的函数 shuffleCards
。我传入的数组是练习中提供给我的数组,它是一组卡片。
当我单击按钮时没有任何反应,我知道这与范围有关,但我不知道如何修改我的代码以使其正常工作。
提前谢谢您。
HTML
<button type="button" id="shuffle" class="shuffle" class="btn btn-lg btn-secondary">Shuffle</button>
JavaScript
//练习中给出的创建一副牌的部分:
const suit = 'hearts';
const cardsWrapper = document.querySelector('.cards-wrapper');
function createCards() {
const cards = [];
// Create an array with objects containing the value and the suit of each card
for (let i = 1; i <= 13; i += 1) {
const cardObject = {
value: i,
suit,
};
cards.push(cardObject);
}
// For each dataObject, create a new card and append it to the DOM
cards.forEach((card, i) => {
const positionFromLeft = i * 15;
const cardElement = document.createElement('div');
cardElement.setAttribute('data-value', card.value);
cardElement.classList.add('card', `${card.suit}-${card.value}`);
cardElement.style.left = `${positionFromLeft}px`;
cardsWrapper.append(cardElement);
});
}
//我写的部分
const shufflebtn = document.getElementById('shuffle');
shufflebtn.addEventListener("click", () => {
shuffleCards(cards);
})
function shuffleCards(array) {
var i = 0
, j = 0
, temp = null
for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1))
temp = array[i]
array[i] = array[j]
array[j] = temp
}
return array
}
最佳答案
对代码做了一些更改,我不是在谈论 html,而是为您的洗牌提供解决方案。
创建了一个 create cards
按钮,该按钮会触发 createCards
函数,然后尝试单击随机播放并查看控制台日志,您可以看到一个随机排列的数组。
注意:在单击“随机播放”之前单击“创建卡片”按钮,因为您可能会记录空数组
我还更改了卡的范围,因为它应该可以被其他功能访问
const suit = 'hearts';
var cards = [];
function createCards() {
for (let i = 1; i <= 13; i += 1) {
const cardObject = {
value: i,
suit,
};
cards.push(cardObject);
}
}
const shufflebtn = document.getElementById('shuffle');
const creatorBtn = document.getElementById('creator');
shufflebtn.addEventListener("click", () => {
cards = shuffleCards(cards);
})
creatorBtn.addEventListener("click", () => {
createCards();
})
function shuffleCards(array) {
var i = 0,
j = 0,
temp = null
for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1))
temp = array[i]
array[i] = array[j]
array[j] = temp
}
console.log(array)
return array;
}
<button type="button" id="shuffle" class="shuffle" class="btn btn-lg btn-secondary">Shuffle</button>
<button type="button" id="creator" class="creator" class="btn btn-lg btn-secondary">create cards</button>
关于javascript - 单击按钮即可洗牌阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128927/