Javascript - 按值删除数组项 [英] Javascript - remove an array item by value

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

问题描述

我的情况:

var id_tag = [1,2,3,78,5,6,7,8,47,34,90];

我想删除 where id_tag = 90 并返回:

I would like to delete where id_tag = 90 and to return:

var id_tag = [1,2,3,78,5,6,7,8,47,34];

我该怎么做?

推荐答案

你会想要使用 JavaScript 的 数组splice方法:

You'll want to use JavaScript's Array splice method:

var tag_story = [1,3,56,6,8,90],
    id_tag = 90,
    position = tag_story.indexOf(id_tag);

if ( ~position ) tag_story.splice(position, 1);

P.S. 有关那个很酷的 ~ 波浪号快捷方式的说明,请参阅此帖子:

P.S. For an explanation of that cool ~ tilde shortcut, see this post:

使用<代码>~ 波浪号与 indexOf 以检查数组中的项目是否存在.

Using a ~ tilde with indexOf to check for the existence of an item in an array.

注意: IE <9 不支持数组上的 .indexOf().如果你想确保你的代码在 IE 中工作,你应该使用 jQuery 的 $.inArray():

Note: IE < 9 does not support .indexOf() on arrays. If you want to make sure your code works in IE, you should use jQuery's $.inArray():

var tag_story = [1,3,56,6,8,90],
    id_tag = 90,
    position = $.inArray(id_tag, tag_story);

if ( ~position ) tag_story.splice(position, 1);

<小时>

如果你想支持 IE <9 但页面上还没有 jQuery,没有必要将它只是用于 $.inArray.你可以改用这个polyfill.

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

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