从数组中删除一个元素,在 Javascript 中指定一个值 [英] Removing an element from an array specifying a value in Javascript

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

问题描述

我已经阅读了这个问题:

I have read this question:

在 JavaScript 中删除数组元素 - 删除与拼接

而且似乎 splice 和 delete 都需要元素的索引才能删除,那么当我有值时如何轻松找到索引?

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.我现在正在使用的过程,我希望这不是正确的方法,是使用 $.each 检查数组中每个元素的值,通过process(用作索引引用),如果该值等于test2",那么我就有了我的索引(以计数器的形式),然后使用 splice 将其删除.

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?

推荐答案

您想使用 splice() 函数删除项目,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); 

工作演示

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

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