如何在JavaScript中从数组中删除特定值?

3
假设我有一个数组
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];

如果我想从anArray中移除value 3,但不知道该值在数组中的位置,我该如何移除它?

注意:我是JavaScript的初学者。


2个回答

6

使用indexOf获取索引,使用splice进行删除:

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
anArray.splice(anArray.indexOf("value 3"), 1);
console.log(anArray);
.as-console-wrapper { max-height: 100% !important; top: auto; }


谢谢...顺便问一下,最后一行是干什么用的? - user11554942
1
你是指CSS中的@shiro13吗?它只是扩展了控制台,让你不必滚动。 - Jack Bashford

3

您可以使用filter

filter将返回一个新的数组,其中包含除了value 3之外的值,这将删除所有的value 3。如果您只想删除第一个value 3,您可以使用其他答案中提到的splice。

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];

const filtered = anArray.filter(val=> val !== 'value 3')

console.log(filtered)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接