この記事では、JavaScript配列の要素を削除する方法を紹介します。
以下の例では、配列の要素を削除するメソッドを独自に定義しています。
例
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var sites = ['apple', 'google', 'サンプル', 'taobao'];
sites.removeByValue('google');
console.log(sites);
// -> ['apple', 'サンプル', 'taobao']
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var sites = ['apple', 'google', 'サンプル', 'taobao'];
sites.removeByValue('google');
console.log(sites);
// -> ['apple', 'サンプル', 'taobao']
試してみる »
使用することもできますarray.spliceメソッドで実現します:
例
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // 2番目のパラメータは削除回数です。1回だけ削除するように設定します。
}
// array = [2, 9]
console.log(array);
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // 2番目のパラメータは削除回数です。1回だけ削除するように設定します。
}
// array = [2, 9]
console.log(array);
試してみる »
以下の例では、配列内の1つまたは複数の要素を削除できるように設定しています。
例
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
試してみる »