【问题标题】:Pop elements out of an array using JS使用JS从数组中弹出元素
【发布时间】:2011-05-31 18:39:40
【问题描述】:

我有一个数组 results = [duplicate, otherdup],其中包含重复项列表

我有一个普通的original_array = [duplicate, duplicate, duplicate, otherdup, otherdup, unique, unique2, unique_etc]

如何遍历 results 数组(列表)并从 original_array 中弹出除一个以外的所有内容,如下所示:

oringal_array = [duplicate, otherdup, unique, unique2, unique_etc]`

【问题讨论】:

    标签: javascript jquery arrays loops


    【解决方案1】:

    一个简单的unique 函数可能如下所示:

    Array.prototype.unique = function() {
       var uniqueArr = [];
       var dict = {};
       for(var i = 0; i < this.length; i++) {
          if(!(this[i] in dict)) {
             uniqueArr.push(this[i]);
             dict[this[i]] = 1;
          }
       }
    
       return uniqueArr;
    };
    

    你可以轻松做到:

    var unique_array = original_array.unique();
    

    【讨论】:

    • 这是否适用于 JQuery?我注意到这个函数中的原型
    • @JZ:是的,这是纯原生 javascript。 Prototype 确实是另一个 javascript 库的名称,但之所以这样命名,是因为它大量使用了 javascript 原生的原型设计。
    【解决方案2】:

    我会使用 John Resig 的 Remove() 方法:

    // Remove() - Completely removes item(s) from Array
    // By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
    
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    
    };
    

    您可以遍历您的数组,只需将要删除的索引传递给 Remove() 函数。

    【讨论】:

    • 这是否适用于 JQuery?我注意到这个函数中的原型
    • 是的。 jQuery 只是一个 JavaScript 库。
    • 我的用例是我需要跟踪我打开的 jQuery UI 对话框的场景。我将对话 ID 存储在一个名为 openDialogs 的数组中。当对话框关闭时,我将使用var index = $.inArray("some-dialog-id", openDialogs); 获取数组中对话框的索引,然后将其传递给 remove() 函数,例如:openDialogs.remove(index);
    • Prototype 不是一个竞争库吗?
    • 不确定,但我知道 jQuery 使用原型。只需打开 jQuery 文件并搜索 prototype = 即可。
    【解决方案3】:

    你看起来像这样吗

    但在调用 pop 之前,您将检查它是否应该通过循环运行来弹出 [ed out !

    http://www.tutorialspoint.com/javascript/array_pop.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多