用JS实现一个数组合并的方法(要求去重)

两个数组,a = [1,2,3], b = [2,3,4],要求合并后的数组为[1,2,3,4]

Array.prototype.unique = function(){
    var a = {};
    for(var i = 0; i < this.length; i++){
        if(typeof a[this[i]] == "undefined")
            a[this[i]] = 1;
    }
    this.length = 0;
    for(var i in a)
        this[this.length] = i;
    return this;
}
var a = [1,2,3];
var b = [2,3,4];
var c = a.concat(b).unique();

两个数组,a = [1,2,3], b = [2,3,4],要求合并后的数组为[1,4]

Array.prototype.unique2 = function(){
    var a = {},
        b = {},
        n = this.length;
    for(var i = 0; i < n; i++){
        if(typeof(b[this[i]]) != "undefined")
            continue;
        if(typeof(a[this[i]]) == "undefined"){
            a[this[i]] = 1;
        }else{
            b[this[i]] = 1;
            delete a[this[i]];
        }
    }
    this.length = 0;
    for(var i in a)
        this[this.length] = i;
    return this;
}
var a = [1,2,3,4];
var b = [2,3,5,7];
var d = a.concat(b).unique2();

你可能感兴趣的:(用JS实现一个数组合并的方法(要求去重))