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

array.remove(value);

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


当前回答

从数组中删除项目的最佳方法是使用过滤法。.filter()返回没有过滤过的项目的新数组。

items = items.filter(e => e.id !== item.id);

这个.filter()将当前项目推到过滤的阵列中。更多信息过滤过滤器 在这里.

其他回答

删除在索引i 上的元素, 不突变原始数组 :

/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
   return Array.from(array).splice(index, 1);
}

// Another way is
function removeElement(array, index) {
   return array.slice(0).splice(index, 1);
}

最简单的方法可能是使用过滤功能。例如:

let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]

例如,您有一个字符数组,想要从数组中删除“A”。

数组有一个过滤方法,可以过滤并只返回您想要的元素。

let CharacterArray = ['N', 'B', 'A'];

我想返回元素 除了"A"。

CharacterArray = CharacterArray.filter(character => character !== 'A');

字符阵列必须是 : ['N', 'B']

使用数组过滤过滤器方法 :

let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];

let value = 511;
array = array.filter(element => element !== value);
console.log(array)

定义:

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