如何按值从数组中删除项目? [英] How to remove item from array by value?
本文介绍了如何按值从数组中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有从 JavaScript 数组中删除项目的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做类似的事情:
removeItem('seven', ary);
我已经研究了 splice()
但这只能通过位置编号删除,而我需要一些东西来通过其值删除项目.
解决方案
您可以使用 indexOf
方法 像这样:
var index = array.indexOf(item);如果(索引!== -1){array.splice(index, 1);}
<块引用>
var array = [1,2,3,4]变量项目 = 3var index = array.indexOf(item);array.splice(index, 1);console.log(array)
Is there a method to remove an item from a JavaScript array?
Given an array:
var ary = ['three', 'seven', 'eleven'];
I would like to do something like:
removeItem('seven', ary);
I've looked into splice()
but that only removes by the position number, whereas I need something to remove an item by its value.
解决方案
You can use the indexOf
method like this:
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
var array = [1,2,3,4]
var item = 3
var index = array.indexOf(item);
array.splice(index, 1);
console.log(array)
这篇关于如何按值从数组中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文