挑战是创建“表情符号”与“表情符号”,但是当我运行此代码时,出现错误TypeError: 'x' is not iterable。(x是随机生成的数字)
let fighters = ["", "", "","", "", "", "", "", "", "", "", "", "", "","", "", ""]
let stageEl = document.getElementById("stage")
let fightButton = document.getElementById("fightButton")
fightButton.addEventListener("click", function() {
const [iOne, iTwo] = Math.floor( Math.random() * fighters.length )
stageEl.textContent = `${fighters[iOne]} VS ${fighters[iTwo]}`
})
Run Code Online (Sandbox Code Playgroud)
问题是这一行:
const [iOne, iTwo] = Math.floor( Math.random() * fighters.length )
Run Code Online (Sandbox Code Playgroud)
右侧为您提供一个数字,您尝试将其迭代为两个变量。请参阅数组解构的文档。
代码应该是:
const iOne = Math.floor( Math.random() * fighters.length )
const iTwo = Math.floor( Math.random() * fighters.length )
Run Code Online (Sandbox Code Playgroud)
或者
const getRandomInt = (length) => Math.floor( Math.random() * length);
const iOne = getRandomInt(fighters.length)
const iTwo = getRandomInt(fighters.length)
Run Code Online (Sandbox Code Playgroud)