我有:

var array = new Array();
array.push("A");
array.push("B");
array.push("C");

我希望能够做到:

array.remove (" B ");

但是没有移除函数。我该怎么做呢?


当前回答

const changedArray = array.filter( function(value) {
  return value !== 'B'
});

或者你可以用:

const changedArray = array.filter( (value) => value === 'B');

changedArray将包含没有值的'B'

其他回答

使用array.splice

/*array.splice(index , howMany[, element1[, ...[, elementN]]])

array.splice(index) // SpiderMonkey/Firefox extension*/

array.splice(1,1)

来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

这只对str list有效,查一下

myStrList.filter(item=> !["deletedValue","deletedValue2"].includes(item))

简单的

array.splice(array.indexOf(item), 1);

简单解决方案(ES6)

如果你没有重复元素

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el === elem);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};   

在线演示(小提琴)

use:

array.splice(2, 1);

这将从数组中删除一项,从索引2开始(第3项)