从数组中删除元素,在Javascript中指定值

时间:2021-09-07 21:17:36

I have read this question:

我读过这个问题:

Deleting array elements in JavaScript - delete vs splice

在JavaScript中删除数组元素 - 删除vs splice

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?

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

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

例如,如果我有一个如下所示的数组:

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

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.

我想删除test2。我现在正在使用的进程,我希望这不是正确的方法,使用$ .each检查数组中每个元素的值,通过进程维护一个计数器(用作索引引用) )如果值等于“test2”,那么我有我的索引(以计数器的形式),然后使用splice将其删除。

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

虽然阵列越来越大,但我认为这将是一个缓慢的过程,但我有什么替代方案?

5 个解决方案

#1


4  

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

你想使用splice()函数来删除项目,indexOf会在数组中找到它:

To Find a specific element in the Array: (to know which to remove)

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

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

Full Example:

完整示例:

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

Working Demo

工作演示

#2


3  

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

indexOf (source):
Returns the first index at which a given element can be found in the array, or -1 if it is not present.

indexOf(source):返回可在数组中找到给定元素的第一个索引,如果不存在,则返回-1。

#3


2  

You can jQuery's $.inArray and get rid of your $.each loop, and it works cross-browser (unlike Array.indexOf):

你可以使用jQuery的$ .inArray并摆脱$ .each循环,它可以跨浏览器工作(与Array.indexOf不同):

var index = $.inArray("test2", ["test1", "test2", "test3"]); // 1

(I realise your question is not tagged with 'jQuery', but you do mention that you're already using an $.each loop).

(我意识到你的问题没有用'jQuery'标记,但你确实提到你已经在使用$ .each循环了)。

#4


1  

You find an element by value using Array#indexOf, and then use the resulting index. Note that older browsers may not have it, so you'll want to check to see if it's there and if not add it — here's some code from MDC that does the check and adds the function if it's not there.

您可以使用Array#indexOf按值找到元素,然后使用生成的索引。请注意,较旧的浏览器可能没有它,因此您需要检查它是否存在,如果没有添加它 - 这里是来自MDC的一些代码进行检查并添加函数(如果它不存在)。

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

Note that if you add things to the Array prototype like that, for..in loops that assume they'll only see array indexes (that is, incorrect but common for..in loops) will start having problems because they'll see the string "indexOf" when they're only expecting to see array indexes, see this blog post for details.

请注意,如果你像这样添加数组原型的东西,for..in循环假设他们只会看到数组索引(也就是说,不正确但常见于.in循环)会开始出问题,因为他们会看到字符串“indexOf”,当他们只希望看到数组索引时,请参阅此博客文章了解详细信息。

#5


0  

underscore.js is a really awesome little library with a lot of good utility functions. In this case #reject would be appropriate.

underscore.js是一个非常棒的小库,具有很多很好的实用功能。在这种情况下#reject是合适的。

http://documentcloud.github.com/underscore/#reject

http://documentcloud.github.com/underscore/#reject

(Although the internal method is of course similar to your manual index lookup and slice/splice).

(虽然内部方法当然类似于手动索引查找和切片/拼接)。

#1


4  

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

你想使用splice()函数来删除项目,indexOf会在数组中找到它:

To Find a specific element in the Array: (to know which to remove)

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

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

Full Example:

完整示例:

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

Working Demo

工作演示

#2


3  

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

indexOf (source):
Returns the first index at which a given element can be found in the array, or -1 if it is not present.

indexOf(source):返回可在数组中找到给定元素的第一个索引,如果不存在,则返回-1。

#3


2  

You can jQuery's $.inArray and get rid of your $.each loop, and it works cross-browser (unlike Array.indexOf):

你可以使用jQuery的$ .inArray并摆脱$ .each循环,它可以跨浏览器工作(与Array.indexOf不同):

var index = $.inArray("test2", ["test1", "test2", "test3"]); // 1

(I realise your question is not tagged with 'jQuery', but you do mention that you're already using an $.each loop).

(我意识到你的问题没有用'jQuery'标记,但你确实提到你已经在使用$ .each循环了)。

#4


1  

You find an element by value using Array#indexOf, and then use the resulting index. Note that older browsers may not have it, so you'll want to check to see if it's there and if not add it — here's some code from MDC that does the check and adds the function if it's not there.

您可以使用Array#indexOf按值找到元素,然后使用生成的索引。请注意,较旧的浏览器可能没有它,因此您需要检查它是否存在,如果没有添加它 - 这里是来自MDC的一些代码进行检查并添加函数(如果它不存在)。

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

Note that if you add things to the Array prototype like that, for..in loops that assume they'll only see array indexes (that is, incorrect but common for..in loops) will start having problems because they'll see the string "indexOf" when they're only expecting to see array indexes, see this blog post for details.

请注意,如果你像这样添加数组原型的东西,for..in循环假设他们只会看到数组索引(也就是说,不正确但常见于.in循环)会开始出问题,因为他们会看到字符串“indexOf”,当他们只希望看到数组索引时,请参阅此博客文章了解详细信息。

#5


0  

underscore.js is a really awesome little library with a lot of good utility functions. In this case #reject would be appropriate.

underscore.js是一个非常棒的小库,具有很多很好的实用功能。在这种情况下#reject是合适的。

http://documentcloud.github.com/underscore/#reject

http://documentcloud.github.com/underscore/#reject

(Although the internal method is of course similar to your manual index lookup and slice/splice).

(虽然内部方法当然类似于手动索引查找和切片/拼接)。