如何按值从数组中删除项? [英] How to remove item from array by value?

查看:94
本文介绍了如何按值从数组中删除项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有从JavaScript数组中删除项目的方法?

Is there a method to remove an item from a JavaScript array?

给定一个数组:

var ary = ['three', 'seven', 'eleven'];

我想做的事情如下:

removeItem('seven', ary);

我查了 splice()但是只能通过位置编号删除,而我需要通过其值删除项目。

I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

推荐答案

你可以使用 indexOf method 像这样:

You can use the indexOf method like this:

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);




注意你需要为IE8及以下版本填充

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

console.log(array)

这篇关于如何按值从数组中删除项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆