Array.splice()でJavaScriptの配列操作
Author: 水卜
Author: 水卜
spliceの英単語としての意味は、
動詞
名詞
配列に対する削除、追加、置換などに使う。
リアクティブにデータを変更しなければならないVue.jsでは特に頻繁に使う。
配列操作はもはやspliceだけでいい。
const arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
const months = ['Jan', 'March', 'April', 'June'];
// index1から0個の要素を削除し、'Feb'を挿入
months.splice(1, 0, 'Feb');
console.log(months);
// ["Jan", "Feb", "March", "April", "June"]
// index4から1個の要素を削除し、'May'を挿入
months.splice(4, 1, 'May');
console.log(months);
// ["Jan", "Feb", "March", "April", "May"]
// 複数挿入
months.splice(0, 0, 'a', 'b');
console.log(months);
// ["a", "b", "Jan", "Feb", "March", "April", "May"]
以下の配列の要素、'b’をその前の’a’と入れ替えたい。
const array = ['a', 'b', 'c', 'd'];
// 入れ替える'b'のindex
const index = array.indexOf('b')
array.splice(index - 1, 2, array[index], array[index - 1]);
console.log(array)
// ['b', 'a', 'c', 'd']
以下の配列の要素、'b’をその後ろの’c’と入れ替えたい
const array = ['a', 'b', 'c', 'd'];
// 入れ替える'b'のindex
const index = array.indexOf('b')
array.splice(index, 2, array[index + 1], array[index]);
console.log(array)
// ['a', 'c', 'b', 'd']
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/splice