如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
此函数从特定位置的数组中删除元素。
array.remove(position);
Array.prototype.remove = function (pos) {
this.splice(pos, 1);
}
var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);
如果您不知道要删除的项目的位置, 请使用这个 :
array.erase(element);
Array.prototype.erase = function(el) {
let p = this.indexOf(el); // indexOf use strict equality (===)
if(p != -1) {
this.splice(p, 1);
}
}
var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);
其他回答
const newArray = oldArray.filter(item => item !== removeItem);
您只需要按元素或索引过滤 :
var num = [5, 6, 5, 4, 5, 1, 5];
var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5
console.log(result1);
console.log(result2);
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
或undefined
作为原型
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(是的,我读了所有其他的答案 却找不到一个结合的答案)includes
和splice
在同一行中。 )
定义:
function RemoveEmptyItems(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) if (arr[i] != null && arr[i].length > 0) result.push(arr[i]);
return result;
}
用法 :
var arr = [1,2,3, "", null, 444];
arr = RemoveEmptyItems(arr);
console.log(arr);
尝试使用删除运算符
例如:
const arr = [10, 20, 30, 40, 50, 60];
delete arr[2]; // It will Delete element present at index 2
console.log( arr ); // [10, 20, undefined , 40, 50, 60]
注:使用删除运算符将会在数组中留下空空空/ 空洞。 它不会提醒数组的长度。 要在元素被删除时更改数组的长度, 请使用复数法 。
希望这能解决你所有的问题