0

对javascript非常陌生,无法弄清楚我做错了什么。试图将classNamea<div>元素分配给 a var,我得到了这个错误。

scripts.js:30 Uncaught TypeError: Cannot read property '0' of undefined
    at checkWinner (scripts.js:30)
    at HTMLDivElement.buttonClick (scripts.js:25)

当我试图弄清楚该属性是否存在时,控制台让我相信它确实存在。这对我来说似乎是相互矛盾的信息。

winLines[0][0].className

"xButt"​

任何帮助表示赞赏。我敢肯定这是基本的东西。这是代码以防万一。

var turns = 0;
var gameButtons = Object.values(document.querySelectorAll('.gameButton'));
var winLines= [
  [gameButtons[0], gameButtons[1], gameButtons[2]]
  /* other arrays go hear */
];

for (let i = 0; i < gameButtons.length; i++) {
  gameButtons[i].textContent = null;
  gameButtons[i].addEventListener('click', buttonClick);
}

function buttonClick(e) {    
  console.log(e.target.id + ": You clicked me!");
  if (turns % 2 == 0) {
    e.target.className = 'xButt';
    e.target.textContent = 'X';
    e.target.style.backgroundColor = 'green';
  } else {
    e.target.className = 'oButt';
    e.target.textContent = 'O';
    e.target.style.backgroundColor = 'blue';
  }
  turns++;
  checkWinner();
}

function checkWinner() {
  for (let i = 0; i <= winLines.length; i++) {
    let markOne = winLines[i][0].className;
    let markTwo = winLines[i][1].className;
    let markThree = winLines[i][2].className;
    if (markOne === markTwo && markOne === markThree) {
      alert("Awww sh********t!");
    }    
  }
}
4

1 回答 1

0

您的循环的迭代次数多于数组的元素。

像这样改变循环:

for (let i = 0; i < winLines.length; i++)

出现未定义错误是因为您正在尝试winLines[1][0]不存在的错误,因为winLines只有一个元素(在索引 0 处)

于 2020-01-09T18:08:39.667 回答