JavaScript对象密钥没有分配给变量?

时间:2019-07-05 10:53:01

标签: javascript tic-tac-toe

我试图将boxSpaces[0]的值分配给函数decalreWinner()中的变量结果,但是分配没有发生。

function assignSpace(mark, box) {
    const image = document.createElement("img");
    const src = mark === "x" ? X_IMAGE_URL : O_IMAGE_URL;
    image.src = src;
    box.appendChild(image);
    box.removeEventListener("click", changeToX);
    const id = parseInt(box.dataset.id);
    boxSpaces[id] = mark;
}

function isGameOver() {
    const length = emptyBoxes.length;

    if (length <= 0) {
        declareWinner();
        return true;
    } else {
        false;
    }
}

function declareWinner() {
    const result = "";
    if (boxSpaces["0"] === boxSpaces["1"] && boxSpaces["1"] === boxSpaces["2"]) {
        result = boxSpaces["0"];
        console.log(result);
    }

    return result;
}

1 个答案:

答案 0 :(得分:0)

您正在使用const来声明一个变量,而您正试图更新它,这是不可能的。将其更改为letvar

function declareWinner() {
  let result = ""; //change it to let or var
  if (boxSpaces["0"] === boxSpaces["1"] && boxSpaces["1"] === boxSpaces["2"]) {
    result = boxSpaces["0"];
    console.log(result);
  }

  return result;
}