JS数组

/**
 * 两个数组取差集
 * eg:
 *  var arr1 = ["1","2","3","4"];
    var arr2 = ["6","5","3","4"];
    arr1.minus(arr2);--> 结果是:["1","2"]
    arr2.minus(arr1);--> 结果是:["6","5"]
 */
Array.prototype.minus = function (arr) {
    var result = new Array();
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = 1;
    }
    for (var j = 0; j < this.length; j++) {
        if (!obj[this[j]])
        {
            obj[this[j]] = 1;
            result.push(this[j]);
        }
    }
    return result;
};
/**
 * 数组去重方式(排序去重)
 */
Array.prototype.unique1 = function(){
    this.sort();
    var res = [this[0]];
    for(var i = 1; i < this.length; i++){
        if(this[i] !== res[res.length - 1]){
            res.push(this[i]);
        }
    }
    return res;
}

 

posted @ 2019-05-27 16:17  Goatherd  阅读(157)  评论(0编辑  收藏  举报