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?

JavaScript学習ログ 配列処理関係のメソッドその1

Last updated at Posted at 2025-04-28

■値の追加と削除

.push()

配列の末尾に要素を追加。

const arrayNum = [10,11,12];
arrayNum.push (13,14);
console.log(arrayNum);
//(5) [10, 11, 12, 13, 14]
//array自体の配列が書き換えららえる。

.unshift()

配列の先頭に要素を追加。

arrayNum.unshift (8,9);
console.log(arrayNum);
//(7) [8, 9, 10, 11, 12, 13, 14]
//arrayNum自体の配列が書き換えらえる。

.pop()

配列の最後の要素を取り出して削除する。引数はとらない。

arrayNum.pop(); 
console.log(arrayNum);
//(6) [8, 9, 10, 11, 12, 13]
// → 最後の「14」が削除される

.shift()

配列の先頭の要素を取り出して削除する。引数はとらない。

arrayNum.shift();
console.log(arrayNum);
//(5) [9, 10, 11, 12, 13]
// → 先頭の「8」が削除される

■配列自体の操作

.join()

配列を区切る文字列の操作。引数に何も入れないと区切り文字はカンマ。引数を入れると指定された文字列が表示される。

joinは配列を変えない(破壊しない)

const array = ['ぶり','はまち','まぐろ'];
array.join();
console.log(array);
//(3) ['ぶり', 'はまち', 'まぐろ']

array.join(' / ');
console.log(array);
//(3) ['ぶり', 'はまち', 'まぐろ']
//配列自体は変えないので['ぶり','はまち','まぐろ']と表示される。

console.log(array.join(' / '));
//ぶり / はまち / まぐろ
  • console.log(array)配列
  • console.log(array.join(' / '))文字列

.fill()

第一引数に指定した要素で配列を埋める。指定した値で元の配列の要素を上書きする。

console.log(array.fill('はまち'));
//(3) ['はまち', 'はまち', 'はまち']
//配列を上書きする

const array02 = new Array(5);
//(5) [空 × 5]

console.log(array02);
console.log(array02.fill('ーーー'));
//(5) ['ーーー', 'ーーー', 'ーーー', 'ーーー', 'ーーー']

console.log(array02.fill('✴︎',4));
//(5) ['ーーー', 'ーーー', 'ーーー', 'ーーー', '✴︎']
//第二引数の数字が(0から数えたときの)先頭位置になる

console.log(array02.fill('✴︎',0,4));
//(5) ['✴︎', '✴︎', '✴︎', '✴︎', '✴︎']
//第三引数の数字が(0から数えたときの)末尾の位置になる

.reverse()

配列の向きを逆にする。

const array03 = ['カレー','西京焼き','蕎麦'];

console.log(array03.reverse());
//['蕎麦', '西京焼き', 'カレー']

console.log(array03);
//['蕎麦', '西京焼き', 'カレー']

.toReversed()

配列の向きを逆にする。配列は上書きされない。2023年に登場した新しいメソッドなので対応ブラウザに注意。

const array04 = ['カレー','西京焼き','蕎麦'];
console.log(array04.toReversed());
//['蕎麦', '西京焼き', 'カレー']
console.log(array04);
//['カレー', '西京焼き', '蕎麦']

.float()

ネスト(入れ子)された配列を平坦化させる。

const array05 = [1,2,[3,4]];
console.log(array05.flat());
//(4) [1, 2, 3, 4]
0
0
1

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?