代码之家  ›  专栏  ›  技术社区  ›  WoodrowShigeru

使用原型就地修改阵列

  •  0
  • WoodrowShigeru  · 技术社区  · 7 年前

    删除重复项 分类 它它起作用了,看起来是这样的:

     // given an example array such as this.
    var names = [ 'Lara', 'Lucy', 'Alexa', 'Vanessa', 'Lucy', 'Brianna', 'Sandra' ];
    
    Array.prototype.clean_up = function(){
        var
            set = []
        ;
        this.forEach(function(item){
            if ( set.indexOf(item) === -1 ) {
                set.push(item);
            }
        });
    
        set.sort();
    
        return set;
    };
    

    我唯一的抱怨是我不得不这样称呼它:

    names = names.clean_up();
    

    如果我可以这样称呼它,我会更喜欢它,比如 Array.sort() (我认为这被称为就地实施)。你怎么能这么做?

    names.clean_up();
    

    编辑:(显然,这属于这里,不属于答案)

    我目前的解决方案如下,但感觉有点无效。我想知道是否可以做得更好。

    Array.prototype.clean_up = function(){
        var
            set = [],
            self = this
        ;
        this.forEach(function(item){
            if ( set.indexOf(item) === -1 ) {
                set.push(item);
            }
        });
    
        set.sort();
    
         // reset and re-fill.
        while (this.length > 0) {
            this.pop();
        }
    
        set.forEach(function(item){
            self.push(item);
        });
    };
    

    对一方和另一方都无效:它一直是 mentioned 多次不应修改原始数组。为什么?

    大堆排序() 然后它表明,语言能够做到这一点,而且 一些 实现似乎“正常”?为什么是 sort() 好的,但自定义函数不是吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   RobG    7 年前

    如果要影响阵列,应查找重复项和 捻接 它们来自阵列。 Array.prototype.indexOf 可以与第二个参数一起使用,从当前元素中搜索并删除重复项,例如。

    Array.prototype.clean = function (){
      // Iterate backwards over array
      this.reduceRight(function(acc, value, index, arr) {
        // If first index of value isn't current index, remove this element
        if (arr.indexOf(value) != index) arr.splice(index, 1);
      }, null);
      // Now sort
      this.sort();
      // Return for chaining
      return this;
    }
    
    var arr = 'aztatffgff'.split('');
    console.log(arr.join());
    console.log(arr.clean().join());

    在数组上向前迭代不起作用,因为当元素被拼接时,元素会被洗牌,因此跳过下一个元素。你也不能仅仅用,比如说, 因为您无法将该新数组分配给 .

    右减速器 可以替换为 对于