よく使うけど、他の言語触ってると忘れがちなのでメモ。
詳細や最新情報は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にしておかないと、要素を削除した上で挿入という動作になる。