假设我有一个数组
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
如果我想从value 3
中删除anArray
,但不知道该值在数组中的位置,该如何删除呢?
注意:我是JavaScript的初学者
答案 0 :(得分:3)
使用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; }
答案 1 :(得分:2)
您可以使用filter
过滤器将为您提供一个除value 3
以外的其他值的新数组,这将删除所有value 3
,如果您只想删除第一个value 3
,则可以使用其他答案中给出的拼接
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
const filtered = anArray.filter(val=> val !== 'value 3')
console.log(filtered)