如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
/**
* Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
*
* @param {Array} array Array to remove value from
* @param {*} value Value to remove
* @returns {Array} Array with `value` removed
*/
export function arrayRemove(array, value) {
for(let i=0; i<array.length; ++i) {
if(array[i] == value) {
let copy = [...array];
copy.splice(i, 1);
return copy;
}
}
return array;
}
其他回答
没必要用indexOf
或splice
。但是,如果只想要删除一个元素的发生,则该元素的性能会更好。
查找并移动( 移动) :
function move(arr, val) {
var j = 0;
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] !== val) {
arr[j++] = arr[i];
}
}
arr.length = j;
}
使用使用indexOf
和splice
(指数):
function indexof(arr, val) {
var i;
while ((i = arr.indexOf(val)) != -1) {
arr.splice(i, 1);
}
}
仅使用splice
(恶作剧):
function splice(arr, val) {
for (var i = arr.length; i--;) {
if (arr[i] === val) {
arr.splice(i, 1);
}
}
}
带有 1000 元素的阵列( 平均超过 10,000 次运行) 的节点js 上的运行时间 :
指数指数慢于移动移动即使通过取消要求indexOf
内复盘,它的表现比移动移动.
Remove all occurrences:
move 0.0048 ms
indexof 0.0463 ms
splice 0.0359 ms
Remove first occurrence:
move_one 0.0041 ms
indexof_one 0.0021 ms
Array.prototype.removeItem = function(a) {
for (i = 0; i < this.length; i++) {
if (this[i] == a) {
for (i2 = i; i2 < this.length - 1; i2++) {
this[i2] = this[i2 + 1];
}
this.length = this.length - 1
return;
}
}
}
var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');
你可以轻而易举地用过滤过滤器方法 :
function remove(arrOriginal, elementToRemove){
return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
这将清除数组中的所有元素, 并且运行速度比slice
和indexOf
.
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 fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');
console.log(fruits);
// -> ['apple', 'carrot', 'orange']
一个非常天真的执行情况如下:
Array.prototype.remove = function(data) {
const dataIdx = this.indexOf(data)
if(dataIdx >= 0) {
this.splice(dataIdx ,1);
}
return this.length;
}
let a = [1,2,3];
// This will change arr a to [1, 3]
a.remove(2);
我从函数返回数组的长度以遵守其他方法,例如Array.prototype.push()
.