如何从数组中删除一个特定值? 类似 :

array.remove(value);

制约:我必须使用核心 JavaScript 。 框架不允许 。


当前回答

这提供了一个前提值, 而不是一个值 。

注:它将更新给定阵列,并返回受影响的行。

用法

var removed = helper.remove(arr, row => row.id === 5 );

var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));

定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义定义的定义

var helper = {
 // Remove and return the first occurrence

 remove: function(array, predicate) {
  for (var i = 0; i < array.length; i++) {
   if (predicate(array[i])) {
    return array.splice(i, 1);
   }
  }
 },

 // Remove and return all occurrences

 removeAll: function(array, predicate) {
  var removed = [];

  for (var i = 0; i < array.length; ) {
   if (predicate(array[i])) {
    removed.push(array.splice(i, 1));
    continue;
   }
   i++;
  }
  return removed;
 },
};

其他回答

弹出 - 从阵列变化的结尾处删除 - 从阵列复件的开头处删除 - 从特定的阵列索引过滤器中删除 - 允许您程序化地从阵列中删除元素

要从数组中删除元素, 要从数组中除去元素, 组合、 过滤和删除

每个阵列都有自己的索引,它有助于用索引删除一个特定元素。

拼盘 () 方法

array.splice(index, 1);    

第一个参数是索引,第二个参数是从该索引中删除的元素数量。

因此,单一个元素,我们用1。

删除方法

delete array[index]

过滤 () 方法

如果您想要删除一个在数组中重复的元素, 那么过滤数组 :

removeAll = array.filter(e => e != elem);

Eleem 是您要从数组中删除的元素, 数组是您的数组名称 。

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)

我也碰到了这样的情况:我不得不从阵列中移除一个元素。 indexof没有在互联网探索器中工作, 因此我分享我的工作 jQuery.inArray () 解决方案 :

var index = jQuery.inArray(val, arr);
if (index > -1) {
    arr.splice(index, 1);
    //console.log(arr);
}

您可以扩展数组对象以定义自定义的删除函数如下:

let let = [1, 2,4,4,4,5,5,45,9;] 数.delete = 函数(价值) { var indexof Target = this.indexof (value) =.indexof(value) = this.if(indexoftaget = = = = = = = = = = y= = y,4,4,4,5,4,459; 数. 数.delet = 函数(val = val indexof Talget = this. indexeof(valent) = = = = = indexget =.indexof = = =. { = indexexuf(val =) { = = indexete = = / / / imme eleteletelete (1) // / / / / 预期输出= / / / tradestrayf delett 删除 2,4,4,4,4,4,4,5,5,5,4,4,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,9/ /