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

array.remove(value);

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


当前回答

删除在索引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);
}

其他回答

我找到了这个博客文章,

9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列

我更喜欢使用过滤器 () :

var filtered_arr = arr.filter(function(ele){
   return ele != value;
})

不可改变和一班制方式:

const newArr = targetArr.filter(e => e !== elementToDelete);

由你决定如何行动。

一种办法是使用复数法,从数组中删除项目:

let array = [1, 2, 3]
array.splice(1, 1);
console.log(array)

// return [1, 3]

但要确保您通过第二个参数,否则最终会删除索引后的全部数组。

第二个办法是使用过滤法,其好处在于它不可改变,这意味着你的主阵列不会被操纵:

const array = [1, 2, 3];
const newArray = array.filter(item => item !== 2)
console.log(newArray)

// return [1, 3]

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

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

. filter () 方法映射为完整的数组, 当我返回真实状态时, 它会将当前项目推到过滤的数组。 在此过滤器中读取更多 。

这是我的简单的代码, 用来使用 复数法删除数组中的具体数据。 复数法将给两个参数。 第一个参数是起始数, 第二个参数是删除Count。 第二个参数用于删除从第一个参数值开始的某个元素 。

let arr = [1, 3, 5, 6, 9];

arr.splice(0, 2);

console.log(arr);