【问题标题】:Removing an element from an array specifying a value in Javascript从数组中删除一个元素,在Javascript中指定一个值
【发布时间】:2011-10-24 08:05:19
【问题描述】:

我已经阅读了这个问题:

Deleting array elements in JavaScript - delete vs splice

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

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

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

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

虽然数组变大了,但我想这将是一个缓慢的过程,但我有什么替代方案?

【问题讨论】:

  • 查看indexOf 了解您想要的内容。

标签: javascript arrays


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    在数组中查找特定元素:知道要删除哪个

    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

    【讨论】:

    • 他知道——他甚至说他正在使用它。他想知道的是如何在splice中找到要使用的索引。
    【解决方案3】:

    您使用Array#indexOf 按值查找元素,然后使用生成的索引。请注意,较旧的浏览器可能没有它,因此您需要检查它是否存在,如果没有添加它 - 来自 MDC 的 here's some code 会进行检查并在不存在时添加该功能。

    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;
        }
    }
    

    请注意,如果您像这样向Array 原型添加东西,假设它们只会看到数组索引的for..in 循环(即incorrect 但常见的for..in 循环)将开始出现问题,因为当他们只希望看到数组索引时,他们会看到字符串“indexOf”,有关详细信息,请参阅this blog post

    【讨论】:

      【解决方案4】:
      var array = ["test1", "test2", "test3"];
      array.splice(array.indexOf("test2"), 1);
      

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

      【讨论】:

        【解决方案5】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2016-05-12
          • 2011-08-17
          • 1970-01-01
          • 1970-01-01
          • 2013-05-27
          • 2018-11-16
          • 2013-10-04
          相关资源
          最近更新 更多