给Array本地对象增加一个原型方法,用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除重复条目的新数组

给Array本地对象增加一个原型方法,用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除重复条目的新数组

思想this对象的具体作用域是在函数执行到它的时候才确定;可以删除数组中的元素并且能返回被删除的对象的数组方法splice;采用两两比较的思想

具体代码

Array.prototype.distinct = function() {
    var ret = [];
    for (var i = 0; i < this.length; i++)
    {
        for (var j = i+1; j < this.length;) {   
            if (this[i] === this[j]) {
                ret.push(this.splice(j, 1));  //splice返回数组,这样是把数组存到了另一个数组里面,即数组元素是数组
            } else {
                j++;
            }
        }
    }
     return ret;
}
//for test
var arr = ['a','b','c','d','b','a','e'];
console.log(arr.distinct());
console.log(arr);

运行结果:

[ [ 'a' ], [ 'b' ] ]
[ 'a', 'b', 'c', 'd', 'e' ]

从运行结果可以看出来,返回的结果的数组元素是数组,这是因为splice返回结果是一个数组,这样是把数组存到了另一个数组里面,即数组元素是数组。

修改:将ret.push(this.splice(j, 1));修改为ret.push(this.splice(j, 1)[0]);

完整代码:

Array.prototype.distinct = function() {
    var ret = [];
    for (var i = 0; i < this.length; i++)
    {
        for (var j = i+1; j < this.length;) {   
            if (this[i] === this[j]) {
                ret.push(this.splice(j, 1)[0]);  //splice返回数组,这样是把数组存到了另一个数组里面,即数组元素是数组
            } else {
                j++;
            }
        }
    }
     return ret;
}
//for test
var arr = ['a','b','c','d','b','a','e'];
console.log(arr.distinct());
console.log(arr);

运行结果:

[ 'a', 'b' ]
[ 'a', 'b', 'c', 'd', 'e' ]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值