【问题标题】:Why is this array undefined in React?为什么这个数组在 React 中没有定义?
【发布时间】:2020-04-20 10:00:04
【问题描述】:

我有以下代码,用于在扫雷游戏中设置地雷,但我在 plantMines() 函数中不断收到错误消息,“TypeError: data[randomx] is undefined”。我是 React 的新手,所以也许我错过了一些简单的东西,但我就是看不出问题出在哪里。

initBoardData(height, width, mines) {
    let data = this.createEmptyArray(height, width);
    data = this.plantMines(data, height, width, mines);
    return data;
}

// Create array of grid
createEmptyArray(height, width) {
    let data = [];

    for (let i = 0; i < height; i++) {
        data.push([]);
        for (let j = 0; j < width; j++) {
            data[i][j] = {
                x: i,
                y: j,
                isMine: false,
                neighbour: 0,
                isRevealed: false,
                isEmpty: false,
                isFlagged: false
            };
        }
    }
    return data;
}

// Place mines on board
plantMines(data, height, width, mines) {
    let randomx, randomy, minesPlanted = 0;

    while (minesPlanted < mines) {
        randomx = this.getRandomNumber(width);
        randomy = this.getRandomNumber(height);

        if (!(data[randomx][randomy].isMine)) {    //--ERROR ON THIS LINE
            data[randomx][randomy].isMine = true;
            minesPlanted++;
        }
    }
    return (data);
}

getRandomNumber(dimension) {
    return Math.floor((Math.random() * 1000) + 1 % dimension);
}

编辑:codesandbox - https://codesandbox.io/s/minesweeper-luono?file=/src/Board.js

【问题讨论】:

标签: javascript arrays reactjs undefined


【解决方案1】:

您在 getRandomNumber 中有错误 - 缺少括号:

getRandomNumber(dimension) {
    return Math.floor(((Math.random() * 1000) + 1) % dimension);
  }

还有一个问题,请使用@dellink 提供的解决方案:

randomx = this.getRandomNumber(height);
randomy = this.getRandomNumber(width);

您必须进行 BOTH 更改,它才能开始工作!

【讨论】:

  • 谢谢,虽然没有解决原来的错误
  • 什么意思?现在有新的错误吗?我测试了它,它似乎有效。
  • 当我进行测试时,我使用的是正方形 - 10/10,但是当你有矩形尺寸时,就会触发错误。现在它得到了修复。
  • 嗯,对我来说仍然没有任何改变
【解决方案2】:

我发现了问题所在。 heightwidth 未正确定义,因此 randomxrandomy 被视为字符串,而不是数字,因此数组定义错误。

【讨论】:

    【解决方案3】:

    您正在尝试不存在数组的索引。因此;你得到undefined 错误。 您可以使用下面或@Enchew 的答案。

    getRandomNumber(dimension) {
       return Math.floor(Math.random() * Math.floor(dimension));
    }
    

    【讨论】:

      【解决方案4】:

      根据您的代码,您应该像这样访问数组:data[randomy][randomx]

      【讨论】:

      • 切换它们并不能解决错误,只需将其更改为“TypeError: data[randomy] is undefined”
      【解决方案5】:

      尝试以这种方式改变

      randomx = this.getRandomNumber(height);
      randomy = this.getRandomNumber(width);
      

      【讨论】:

      • 感谢您的建议,虽然它似乎没有什么不同
      猜你喜欢
      • 2013-05-11
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多