【问题标题】:How to write a multidimensional array inside a class in JavaScript?如何在 JavaScript 中的类中编写多维数组?
【发布时间】:2021-07-21 17:20:03
【问题描述】:

所以基本上,我正在为我参与的 Discord 机器人项目编写井字游戏。我只希望board[]; 是一个多维数组。我该怎么做?

代码如下:

require('dotenv').config();

const { Client } = require('discord.js');
const client = new Client();
const PREFIX = process.env.DISCORD_BOT_PREFIX;

class TicTacToe {
    /* here's the variable */
    board[];
    boardSize;
    #emptyPiece;
    #firstPiece;
    #secondPiece;

    constructor(boardSize, emptyPiece, firstPiece, secondPiece) {
        this.boardSize = boardSize;
        this.#emptyPiece = emptyPiece;
        this.#firstPiece = firstPiece;
        this.#secondPiece = secondPiece;

        /* Initializing it here */
        for (let i = 0; i < boardSize; i++)
            for (let j = 0; j < boardSize; j++)
                this.board[i][j] = emptyPiece;
    }

    isBoardEmpty() {
        for (let i = 0; i < this.boardSize; i++)
            for (let j = 0; j < this.boardSize; j++)
                if (this.board[i][j] !== this.#emptyPiece) return false;

        return true;
    }

    isPieceEmpty(x, y) {
        return this.board[x][y] === this.#emptyPiece;
    }
}

let ticTacToe = new TicTacToe(3, '-', 'x', 'o');

client.on('message', (message) => {
    if (message.author.bot && !message.content.startsWith(PREFIX)) return;

    const [COMMAND_NAME, ...args] = message.content.toLowerCase().trim().substring(PREFIX.length).split(/\s+/g);

    if (COMMAND_NAME === 'showBoard') message.channel.send(ticTacToe.board);
});

client.login(process.env.DISCORD_BOT_TOKEN).then(r => {
    console.log(`${client.user.tag} logged in!`);
});

【问题讨论】:

  • 在类中,它只是board = [],但为什么不在构造函数中将其设为this变量,即this.board = []?如果你想要一个预先分配的大小,你想要board = [...Array(boardSize)].map(() =&gt; Array(boardSize).fill(0))board = [[0,0,0],[0,0,0],[0,0,0]] 之类的东西吗?
  • 你必须用[]初始化数组和数组的每一行。

标签: javascript node.js arrays multidimensional-array


【解决方案1】:

您可以创建一个给定大小的数组,然后使用.map() 将每个元素更改为给定大小的数组。

let size = 3;

let board = Array.from({
  length: size
}).map(() => Array(size).fill("-"));

console.log(board);

这就是你的构造函数中的样子

constructor(boardSize, emptyPiece, firstPiece, secondPiece) {
    this.boardSize = boardSize;
    this.#emptyPiece = emptyPiece;
    this.#firstPiece = firstPiece;
    this.#secondPiece = secondPiece;

    /* Initializing it here */
    this.board = Array.from({
      length: size
    }).map(() => Array(size).fill("-"));

}

【讨论】:

    【解决方案2】:

    一个数组,每个元素也是一个数组。
    所以如果你想改变中间的零,你做board[1][1] = 1

    let board = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ];
    

    【讨论】:

      猜你喜欢
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2022-01-19
      • 2015-08-13
      • 2012-05-14
      • 1970-01-01
      相关资源
      最近更新 更多