从数组指定的Javascript值删除元素 [英] Removing an element from an array specifying a value in Javascript

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

问题描述

我已经阅读了这个问题:

I have read this question:

JavaScript的数组删除

和看来,无论剪接和删除需要的元素的索引,以去除,所以我怎么能轻易找到索引时我的价值?

And it appears that both splice and delete require an index of the element in order to remove, so how can I easily find the index when I have the value?

例如,如果我有一个数组,看起来像这样:

For example if I have an array that looks like this:

["test1", "test2", "test3"]

和我想删除TEST2。我现在使用的过程中,我很希望是不是这样做的正确方法,是使用 $。每个检查每个元素的值在数组中,保持整个过程的计数器(作为参考指标),如果该值等于测试2,然后我有我的索引(在柜台的形式),然后使用拼接将其删除。

and I want to remove test2. The process I am using right now, which I'm hoping isn't the correct way to do it, is using $.each checking the value of each element in the array, maintaining a counter through the process (used as the index reference) and if the value is equal to "test2", then I have my index (in form of the counter) and then use splice to remove it.

尽管阵列变大,我可以想象这将是一个缓慢的过程,但做的选择我?

While the array grows larger, I would imagine this would be a slow process, but what alternatives do I have?

推荐答案

您要使用的剪接()函数删除的项目,的indexOf 会发现它在数组中

You want to use the splice() function to remove the item, indexOf will find it in the array:

查找在数组中的特定元素:知道其中删除的)

var index = array.indexOf('test2'); 

完整的例子:

var array = ['test1', 'test2', 'test3'];
var value_to_remove = 'test2';
array.splice(array.indexOf(value_to_remove), 1); 

工作演示

Working Demo

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

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