0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】二次元配列について

Last updated at Posted at 2023-04-26

はじめに

この記事はJS初級者が中級者を目指して学習した内容のメモであることをご承知おき下さい

二次元配列とは

配列の要素がさらに配列であるようなデータ構造のことを指す。
行と列を持つグリッドや表の形式でデータを格納するときに便利。

サンプルコード

// 定義方法
const twoDimensionalArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// 各要素へのアクセス方法
console.log(twoDimensionalArray[0][0]); // 1
console.log(twoDimensionalArray[1][1]); // 5
console.log(twoDimensionalArray[2][2]); // 9

二次元配列をループで処理する方法

const twoDimensionalArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

for (let i = 0; i < twoDimensionalArray.length; i++) {
  for (let j = 0; j < twoDimensionalArray[i].length; j++) {
    console.log(`行: ${i}, 列: ${j}, 値: ${twoDimensionalArray[i][j]}`);
  }
}

上記は以下のように表示される

行: 0, 列: 0, 値: 1
行: 0, 列: 1, 値: 2
行: 0, 列: 2, 値: 3
行: 1, 列: 0, 値: 4
行: 1, 列: 1, 値: 5
行: 1, 列: 2, 値: 6
行: 2, 列: 0, 値: 7
行: 2, 列: 1, 値: 8
行: 2, 列: 2, 値: 9
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?