LoginSignup
1
1

More than 3 years have passed since last update.

JavaScript 配列操作

Last updated at Posted at 2019-08-05

よく使うけど、他の言語触ってると忘れがちなのでメモ。

詳細や最新情報はMDNを参照してください。

配列への追加

追加にはpushを使う。

let array = ["1st"];
array.push("substream"); // 2

console.log(array); // ["1st", "substream"]

PHPのようにarray[] = "addition"はできない。

配列から削除

配列の最後を削除する場合はpop、最初を削除する場合はshiftを使う。

let array = ["2nd", "3rd", "4th"];
array.pop(); // "4th"
console.log(array); // ["2nd", "3rd"]

array.shift(); // "2nd"
console.log(array); // ["3rd"]

また、位置を指定した削除にはspliceを使う。
引数の1つ目には開始位置、2つ目は削除する要素数を指定する。

let array = ["5th", "6th", "7th"];
array.splice(1, 1); // ["6th"]

console.log(array); // ["5th", "7th"];

添字ではなく文字列で削除を行う場合はindexOfを使う。

let array = ["8th", "9th", "10th"];
let index = array.indexOf("9th"); // 1
array.splice(index, 1); // ["9th"]

console.log(array); // ["8th", "10th"]

配列に挿入

また、spliceは途中に要素を挿入することも出来る。
挿入を行う場合は引数の3つ目以降に追加する要素を指定する。

let array = ["RED", "DistorteD"];
array.splice(1, 0, "HAPPY SKY"); // []

console.log(array); // ["RED", "HAPPY SKY", "DistorteD"]

引数の2つ目を0にしておかないと、要素を削除した上で挿入という動作になる。

1
1
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
1
1