簡體   English   中英

如何在 JavaScript 的類中編寫多維數組?

[英]How to write a multidimensional array inside a class in JavaScript?

所以基本上,我正在為我參與的 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!`); });

您可以創建一個給定大小的數組,然后使用.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("-"));

}

每個元素的數組也是一個數組。
所以如果你想改變中間的零,你做board[1][1] = 1

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM