如何从数组中删除特定项目?

JavaScript

Near神奇

2020-03-09

我有一个数字数组,并且使用该.push()方法向其中添加元素。

有没有一种简单的方法可以从数组中删除特定元素?

相当于-

array.remove(number);

我必须使用核心 JavaScript-不允许使用框架。

第131篇《如何从数组中删除特定项目?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

45个回答
Eva梅 2020.03.09

查看此代码。它适用于所有主流浏览器

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

调用此功能

remove_item(array,value);
GreenTonyL 2020.03.09

您可以使用filter方法轻松完成此操作

function remove(arrOriginal, elementToRemove){
    return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));

这消除了来自阵列的所有元素和也工作速度比的组合sliceindexOf

神无Green前端 2020.03.09

Underscore.js可用于解决多个浏览器的问题。如果存在,它将使用内置浏览器方法。如果缺少它们(例如在较旧的Internet Explorer版本中),则使用其自己的自定义方法。

一个简单的示例(从网站上)从数组中删除元素:

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
杨天栾 2020.03.09

John Resig 发布了一个很好的实现

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

如果您不想扩展全局对象,则可以执行以下操作:

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

但是,我发布此消息的主要原因是为了警告用户不要该页面的评论(2007年12月14日)中建议的替代实现:

Array.prototype.remove = function(from, to){
  this.splice(from, (to=[0,from||1,++to-from][arguments.length])<0?this.length+to:to);
  return this.length;
};

一开始它似乎运行良好,但是经过一个痛苦的过程,我发现当尝试删除数组中倒数第二个元素时它失败了。例如,如果您有一个包含10个元素的数组,并且尝试使用此元素删除第9个元素:

myArray.remove(8);

您最终得到一个8元素数组。不知道为什么,但是我确认John的原始实现没有这个问题。

西里阳光 2020.03.09

无需使用indexOfsplice但是,如果只想删除一个元素,它的性能会更好。

查找并移动(移动):

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;
}

使用indexOfsplice(indexof):

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个元素的数组的nodejs上的运行时(平均运行10000次以上):

indexof大约比move慢10倍即使除去调用改进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
小哥Pro梅 2020.03.09

A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given:

const items = [1, 2, 3, 4];
const index = 2;

Then:

items.filter((x, i) => i !== index);

Yielding:

[1, 2, 4]

You can use Babel and a polyfill service to ensure this is well supported across browsers.

Gil启人 2020.03.09

You have 1 to 9 in the array, and you want remove 5. Use the below code:

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return m !== 5;
});

console.log("new Array, 5 removed", newNumberArray);


If you want to multiple values. Example:- 1,7,8

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return (m !== 1) && (m !== 7) && (m !== 8);
});

console.log("new Array, 1,7 and 8 removed", newNumberArray);


If you want to remove an array value in an array. Example: [3,4,5]

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];

var newNumberArray = numberArray.filter(m => {
    return !removebleArray.includes(m);
});

console.log("new Array, [3,4,5] removed", newNumberArray);

Includes supported browser is link.

老丝镜风 2020.03.09

Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations.


This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value).

Array.prototype.destroy = function(obj){
    // Return null if no objects were found and removed
    var destroyed = null;

    for(var i = 0; i < this.length; i++){

        // Use while-loop to find adjacent equal objects
        while(this[i] === obj){

            // Remove this[i] and store it within destroyed
            destroyed = this.splice(i, 1)[0];
        }
    }

    return destroyed;
}

Usage:

var x = [1, 2, 3, 3, true, false, undefined, false];

x.destroy(3);         // => 3
x.destroy(false);     // => false
x;                    // => [1, 2, true, undefined]

x.destroy(true);      // => true
x.destroy(undefined); // => undefined
x;                    // => [1, 2]

x.destroy(3);         // => null
x;                    // => [1, 2]
Green神乐 2020.03.09

You should never mutate your array. As this is against the functional programming pattern. You can create a new array without referencing the array you want to change data of using the ECMAScript 6 method filter;

var myArray = [1, 2, 3, 4, 5, 6];

Suppose you want to remove 5 from the array, you can simply do it like this:

myArray = myArray.filter(value => value !== 5);

This will give you a new array without the value you wanted to remove. So the result will be:

 [1, 2, 3, 4, 6]; // 5 has been removed from this array

For further understanding you can read the MDN documentation on Array.filter.

小卤蛋Tony 2020.03.09

If you have complex objects in the array you can use filters? In situations where $.inArray or array.splice is not as easy to use. Especially if the objects are perhaps shallow in the array.

E.g. if you have an object with an Id field and you want the object removed from an array:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});
Pro神奇 2020.03.09

ES6 & without mutation: (October 2016)

const removeByIndex = (list, index) =>
      [
        ...list.slice(0, index),
        ...list.slice(index + 1)
      ];
         
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
      
console.log(output)

Eva梅 2020.03.09

Check out this code. It works in every major browser.

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

Call this function

remove_item(array,value);
GO小胖 2020.03.09

OK, for example you have the array below:

var num = [1, 2, 3, 4, 5];

And we want to delete number 4. You can simply use the below code:

num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];

If you are reusing this function, you write a reusable function which will be attached to the native array function like below:

Array.prototype.remove = Array.prototype.remove || function(x) {
  const i = this.indexOf(x);
  if(i===-1)
      return;
  this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}

But how about if you have the below array instead with a few [5]s in the array?

var num = [5, 6, 5, 4, 5, 1, 5];

We need a loop to check them all, but an easier and more efficient way is using built-in JavaScript functions, so we write a function which use a filter like below instead:

const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]

Also there are third-party libraries which do help you to do this, like Lodash or Underscore. For more information, look at lodash _.pull, _.pullAt or _.without.

西里A 2020.03.09

Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods.

A simple example to remove elements from array (from the website):

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
TomMandy 2020.03.09

You can do it easily with the filter method:

function remove(arrOriginal, elementToRemove){
    return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));

This removes all elements from the array and also works faster than a combination of slice and indexOf.

GilJinJin 2020.03.09

There is no need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element.

Find and move (move):

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;
}

Use indexOf and splice (indexof):

function indexof(arr, val) {
  var i;
  while ((i = arr.indexOf(val)) != -1) {
    arr.splice(i, 1);
  }
}

Use only splice (splice):

function splice(arr, val) {
  for (var i = arr.length; i--;) {
    if (arr[i] === val) {
      arr.splice(i, 1);
    }
  }
}

Run-times on nodejs for array with 1000 elements (average over 10000 runs):

indexof is approximately 10x slower than move. Even if improved by removing the call to indexOf in splice it performs much worse than move.

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
Itachi理查德 2020.03.09

我不知道你的array.remove(int)表现如何我可以想到您可能想要的三种可能性。

要在索引处删除数组的元素i

array.splice(i, 1);

如果number要从数组中删除每个具有值的元素

for(var i = array.length - 1; i >= 0; i--) {
    if(array[i] === number) {
        array.splice(i, 1);
    }
}

如果只想使索引处的元素i不再存在,但又不想更改其他元素的索引:

delete array[i];
神奇Jim 2020.03.09

有两种主要方法:

  1. splice()anArray.splice(index, 1);

  2. 删除delete anArray[index];

对数组使用delete时要小心。这对删除对象的属性很有用,但对数组却不太好。最好splice用于数组。

请记住,当您使用delete数组时,可能会得到错误的结果anArray.length换句话说,delete将删除该元素,但不会更新length属性的值。

您还可以期望在使用delete后索引号中出现空洞,例如,最终可能会具有使用delete之前的索引1、3、4、8、9、11和长度。在这种情况下,所有索引for循环都会崩溃,因为索引不再是顺序的。

如果delete由于某种原因而被迫使用,则for each在需要遍历数组时应使用循环。实际上for,如果可能,请始终避免使用索引循环。这样,代码将更健壮,并且不易出现索引问题。

A小卤蛋Pro 2020.03.09

一个朋友在Internet Explorer 8中遇到问题,向我展示了他的工作。我告诉他这是错误的,他告诉我他在这里得到了答案。当前的最佳答案不能在所有浏览器(例如Internet Explorer 8)中都起作用,并且只会删除该项目的第一个匹配项。

从阵列中删除所有实例

function remove(arr, item) {
    for (var i = arr.length; i--;) {
        if (arr[i] === item) {
            arr.splice(i, 1);
        }
    }
}

它向后循环遍历数组(因为索引和长度会随着项目的删除而改变),并在找到后删除该项目。它适用于所有浏览器。

樱理查德 2020.03.09

这取决于您是否要保留空白点。

如果您确实想要一个空插槽,则可以删除:

delete array[index];

如果不这样做,则应使用splice方法:

array.splice(index, 1);

而且,如果您需要该项目的值,则可以只存储返回的数组的元素:

var value = array.splice(index, 1)[0];

如果您想按某种顺序进行操作,则可以将其array.pop()用于最后一个或array.shift()第一个(并且两者也都返回该项目的值)。

而且,如果您不知道该项目的索引,可以使用array.indexOf(item)来获取它(在if()中获取一个项目或在while()中获取所有项目)。array.indexOf(item)返回索引或-1(如果找不到)。 

古一斯丁猴子 2020.03.09

使用查找index要删除的数组元素的indexOf,然后使用删除该索引splice

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

的第二个参数splice是要删除的元素数。注意,splice将在适当位置修改数组并返回一个包含已删除元素的新数组。

Eva梅 2020.03.09

查看此代码。它适用于所有主流浏览器

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

调用此功能

remove_item(array,value);
Eva梅 2020.03.09

查看此代码。它适用于所有主流浏览器

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

调用此功能

remove_item(array,value);
Eva梅 2020.03.09

查看此代码。它适用于所有主流浏览器

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

调用此功能

remove_item(array,value);
Eva梅 2020.03.09

查看此代码。它适用于所有主流浏览器

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

调用此功能

remove_item(array,value);
逆天乐樱 2020.03.09

我知道已经有很多答案了,但是其中许多似乎使问题变得过于复杂。这是删除键的所有实例的一种简单的递归方法-调用self直到找不到索引。是的,它仅可在带有的浏览器中使用indexOf,但它很简单并且可以轻松地进行多填充。

单机功能

function removeAll(array, key){
    var index = array.indexOf(key);

    if(index === -1) return;

    array.splice(index, 1);
    removeAll(array,key);
}

原型法

Array.prototype.removeAll = function(key){
    var index = this.indexOf(key);

    if(index === -1) return;

    this.splice(index, 1);
    this.removeAll(key);
}
さ恋旧る 2020.03.09

您的数组中有1到9,并且要删除5。使用以下代码:

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return m !== 5;
});

console.log("new Array, 5 removed", newNumberArray);


如果要多个值。范例:-1,7,8

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return (m !== 1) && (m !== 7) && (m !== 8);
});

console.log("new Array, 1,7 and 8 removed", newNumberArray);


如果要删除数组中的数组值。范例:[3,4,5]

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];

var newNumberArray = numberArray.filter(m => {
    return !removebleArray.includes(m);
});

console.log("new Array, [3,4,5] removed", newNumberArray);

包括受支持的浏览器是link

null 2020.03.09

一种更现代的ECMAScript 2015(以前称为Harmony或ES 6)方法。鉴于:

const items = [1, 2, 3, 4];
const index = 2;

然后:

items.filter((x, i) => i !== index);

屈服:

[1, 2, 4]

您可以使用Babelpolyfill服务来确保跨浏览器很好地支持此功能。

樱十三 2020.03.09

更新:仅当您无法使用ECMAScript 2015(以前称为ES6)时,才建议使用此方法。如果可以使用它,这里的其他答案将提供更整洁的实现。


这里的要点将解决您的问题,并删除所有出现的参数,而不仅仅是1(或指定值)。

Array.prototype.destroy = function(obj){
    // Return null if no objects were found and removed
    var destroyed = null;

    for(var i = 0; i < this.length; i++){

        // Use while-loop to find adjacent equal objects
        while(this[i] === obj){

            // Remove this[i] and store it within destroyed
            destroyed = this.splice(i, 1)[0];
        }
    }

    return destroyed;
}

用法:

var x = [1, 2, 3, 3, true, false, undefined, false];

x.destroy(3);         // => 3
x.destroy(false);     // => false
x;                    // => [1, 2, true, undefined]

x.destroy(true);      // => true
x.destroy(undefined); // => undefined
x;                    // => [1, 2]

x.destroy(3);         // => null
x;                    // => [1, 2]
Gil番长 2020.03.09

我想根据ECMAScript 6回答假设您有一个如下数组:

let arr = [1,2,3,4];

如果要删除像这样的特殊索引2,请编写以下代码:

arr.splice(2, 1); //=> arr became [1,2,4]

但是,如果您要删除一个特殊项目,3而又不知道其索引,请执行以下操作:

arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]

提示:请使用箭头函数进行过滤器回调,除非您得到一个空数组。

Pro老丝 2020.03.09

您绝对不应更改数组。因为这与功能编程模式相反。您可以使用ECMAScript 6方法创建新数组,而无需引用要更改数据的数组filter

var myArray = [1, 2, 3, 4, 5, 6];

假设您5要从数组中删除,只需执行以下操作:

myArray = myArray.filter(value => value !== 5);

这将为您提供一个新数组,而没有您要删除的值。因此结果将是:

 [1, 2, 3, 4, 6]; // 5 has been removed from this array

为了进一步理解,您可以阅读Array.filter上的MDN文档

理查德村村小宇宙 2020.03.09

如果数组中有复杂的对象,可以使用过滤器吗?在$ .inArray或array.splice不太容易使用的情况下。特别是如果对象在数组中可能很浅。

例如,如果您有一个带有Id字段的对象,并且希望将该对象从数组中删除:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});
StafanHarry 2020.03.09

我刚接触JavaScript,需要此功能。我只是这样写:

function removeFromArray(array, item, index) {
  while((index = array.indexOf(item)) > -1) {
    array.splice(index, 1);
  }
}

然后,当我想使用它时:

//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];

//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");

输出-如预期。[“ item1”,“ item1”]

您可能与我有不同的需求,因此您可以轻松地对其进行修改以适合他们。我希望这可以帮助别人。

乐A 2020.03.09

ES6且无突变:(2016年10月)

const removeByIndex = (list, index) =>
      [
        ...list.slice(0, index),
        ...list.slice(index + 1)
      ];
         
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
      
console.log(output)

null 2020.03.09

好的,例如,您具有以下数组:

var num = [1, 2, 3, 4, 5];

我们要删除数字4。您可以简单地使用以下代码:

num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];

如果要重用此函数,请编写一个可重用的函数,该函数将附加到本数组函数,如下所示:

Array.prototype.remove = Array.prototype.remove || function(x) {
  const i = this.indexOf(x);
  if(i===-1)
      return;
  this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}

但是,如果有下面的数组而不是数组中有[5]个,那又如何呢?

var num = [5, 6, 5, 4, 5, 1, 5];

我们需要一个循环来检查它们,但是更简单,更有效的方法是使用内置的JavaScript函数,因此我们编写了一个使用如下过滤器的函数:

const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]

此外,还有第三方库(如Lodash或Underscore)可以帮助您完成此任务。有关更多信息,请查看lodash _.pull,_。pullAt或_.without。

Eva梅 2020.03.09

查看此代码。它适用于所有主流浏览器

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

调用此功能

remove_item(array,value);
杨天栾 2020.03.09

John Resig 发布了一个很好的实现

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

如果您不想扩展全局对象,则可以执行以下操作:

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

但是,我发布此消息的主要原因是为了警告用户不要该页面的评论(2007年12月14日)中建议的替代实现:

Array.prototype.remove = function(from, to){
  this.splice(from, (to=[0,from||1,++to-from][arguments.length])<0?this.length+to:to);
  return this.length;
};

一开始它似乎运行良好,但是经过一个痛苦的过程,我发现当尝试删除数组中倒数第二个元素时它失败了。例如,如果您有一个包含10个元素的数组,并且尝试使用此元素删除第9个元素:

myArray.remove(8);

您最终得到一个8元素数组。不知道为什么,但是我确认John的原始实现没有这个问题。

神无Green前端 2020.03.09

Underscore.js可用于解决多个浏览器的问题。如果存在,它将使用内置浏览器方法。如果缺少它们(例如在较旧的Internet Explorer版本中),则使用其自己的自定义方法。

一个简单的示例(从网站上)从数组中删除元素:

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
GreenTonyL 2020.03.09

您可以使用filter方法轻松完成此操作

function remove(arrOriginal, elementToRemove){
    return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));

这消除了来自阵列的所有元素和也工作速度比的组合sliceindexOf

西里阳光 2020.03.09

无需使用indexOfsplice但是,如果只想删除一个元素,它的性能会更好。

查找并移动(移动):

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;
}

使用indexOfsplice(indexof):

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个元素的数组的nodejs上的运行时(平均运行10000次以上):

indexof大约比move慢10倍即使除去调用改进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
A小卤蛋Pro 2020.03.09

一个朋友在Internet Explorer 8中遇到问题,向我展示了他的工作。我告诉他这是错误的,他告诉我他在这里得到了答案。当前的最佳答案不能在所有浏览器(例如Internet Explorer 8)中都起作用,并且只会删除该项目的第一个匹配项。

从阵列中删除所有实例

function remove(arr, item) {
    for (var i = arr.length; i--;) {
        if (arr[i] === item) {
            arr.splice(i, 1);
        }
    }
}

它向后循环遍历数组(因为索引和长度会随着项目的删除而改变),并在找到后删除该项目。它适用于所有浏览器。

小小猴子 2020.03.09

我不知道你的array.remove(int)表现如何我可以想到您可能想要的三种可能性。

要在索引处删除数组的元素i

array.splice(i, 1);

如果number要从数组中删除每个具有值的元素

for(var i = array.length - 1; i >= 0; i--) {
    if(array[i] === number) {
        array.splice(i, 1);
    }
}

如果只想使索引处的元素i不再存在,但又不想更改其他元素的索引:

delete array[i];
神奇Jim 2020.03.09

有两种主要方法:

  1. splice()anArray.splice(index, 1);

  2. 删除delete anArray[index];

对数组使用delete时要小心。这对删除对象的属性很有用,但对数组却不太好。最好splice用于数组。

请记住,当您使用delete数组时,可能会得到错误的结果anArray.length换句话说,delete将删除该元素,但不会更新length属性的值。

您还可以期望在使用delete后索引号中出现空洞,例如,最终可能会具有使用delete之前的索引1、3、4、8、9、11和长度。在这种情况下,所有索引for循环都会崩溃,因为索引不再是顺序的。

如果delete由于某种原因而被迫使用,则for each在需要遍历数组时应使用循环。实际上for,如果可能,请始终避免使用索引循环。这样,代码将更健壮,并且不易出现索引问题。

樱理查德 2020.03.09

这取决于您是否要保留空白点。

如果您确实想要一个空插槽,则可以删除:

delete array[index];

如果不这样做,则应使用splice方法:

array.splice(index, 1);

而且,如果您需要该项目的值,则可以只存储返回的数组的元素:

var value = array.splice(index, 1)[0];

如果您想按某种顺序进行操作,则可以将其array.pop()用于最后一个或array.shift()第一个(并且两者也都返回该项目的值)。

而且,如果您不知道该项目的索引,可以使用array.indexOf(item)来获取它(在if()中获取一个项目或在while()中获取所有项目)。array.indexOf(item)返回索引或-1(如果找不到)。 

蛋蛋神乐 2020.03.09

使用查找index要删除的数组元素的indexOf,然后使用删除该索引splice

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

的第二个参数splice是要删除的元素数。注意,splice将在适当位置修改数组并返回一个包含已删除元素的新数组。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android