[英]How to write a multidimensional array inside a class in JavaScript?
So basically, I am writing a Tic Tac Toe game for a Discord bot project I took.所以基本上,我正在为我参与的 Discord 机器人项目编写井字游戏。 I just want the
board[];
我只想要
board[];
to be a multidimensional array.成为一个多维数组。 How do I do it?
我该怎么做?
Here's the code:这是代码:
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!`); });
You can create an array with a given size, then use .map()
to change each element to an array of a given size.您可以创建一个给定大小的数组,然后使用
.map()
将每个元素更改为给定大小的数组。
let size = 3; let board = Array.from({ length: size }).map(() => Array(size).fill("-")); console.log(board);
This is what it would look like in your constructor这就是你的构造函数中的样子
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("-"));
}
An array with each element also an array.每个元素的数组也是一个数组。
So if you want to change the middle zero, you do board[1][1] = 1
所以如果你想改变中间的零,你做
board[1][1] = 1
let board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.