js数组去重的四种方法

//第一种方法
Array.prototype.removeDuplicate = function() {
    var n = [];
    for (var i = 0; i < this.length; i++) {
        if (n.indexOf(this[i]) == -1) {
            n.push(this[i]);
        }
    }
    return n;
}
var arr = [1, 2, 3, 3, 2, '我', '我', 34, '我', NaN, NaN];
var m1 = arr.removeDuplicate();
console.log(m1); //[1, 2, 3, "我", 34, "我的", NaN, NaN]
document.write("第一种方法<br>");
document.write("数组值:"+arr + "<br>");
document.write("删除重复后:"+m1);
//第二种方法
Array.prototype.removeDuplicate = function() {
    var n = [];
    for (var i = 0; i < this.length - 1; i++) {
        if (this.indexOf(this[i]) == i) {
            n.push(this[i]);
        }
    }
    return n;
}
var m2 = arr.removeDuplicate();
console.log(m2); //[1, 2, 3, "我", 34, "我的"]
//第三种方法
Array.prototype.removeDuplicate = function() {
    var n = [],
    m = {};
    for (var i = 0; i < this.length; i++) {
        if (!m[this[i]]) {
            m[this[i]] = true;
            n.push(this[i]);
        }
    }
    return n;
}
var m3 = arr.removeDuplicate();
console.log(m3); //[1, 2, 3, "我", 34, "我的", NaN]
//第四种方法
Array.prototype.removeDuplicate = function() {
    var n = [];
    this.sort();
    for (var i = 0; i < this.length; i++) {
        if (this[i] != this[i + 1]) {
            n.push(this[i]);
        }
    }
    return n;
}
var m4 = arr.removeDuplicate();
console.log(m4); //[1, 2, 3, 34, NaN, NaN, "我", "我的"]    

  

posted @ 2017-04-03 00:09  ghfjj  阅读(218)  评论(0编辑  收藏  举报