JS 数组间的操作

JS 数组间的操作(交集,并集、差集)

以下是js数组之间常用的操作,如交集,并集、差集等。

迭代

each是一个集合迭代函数,可以将一个函数作为参数和一组可以选的参数。依次将集合的每一个元素和可选参数用函数进行计算。

 /**fn 进行迭代判定的函数
   *零个或多个可选的用户自定义参数 */
Array.prototype.each = function(fn){
    fn = fn || Functuon.K;
    var a = [];
    var args = Array.prototype.slice.call(arguments,10);
    for(var i=0;i<this.length;i++){
        var res = fn.apply(this,this[i],i).concat(agrs);
        if(res != null) {
            a.push(res);
        }
    }
}

Array.prototype.slice(arguments, 0); 这个写法可以用于function() {} 内,这样可以将函数的参数列表转换成一个真正的数组。

例:var a = [1,2,3,4].each(function(x){return x > 2 ? x : null});

唯一化数组

/** 得到一个数组不重复的元素集合**/
Array.prototype.uniquelize = function(){
    var ra = new Array();
    for(var i=0; i<this.length;i++){
        if(!ra.contains(this[i])){
            ra.push[this[i]);           
        }
    }
  return ra;
}

差集


Array.minus = function(a, b){
return a.uniquelize().each(function(o){
return b.contains(o) ? null : o
});
};

并集

Array.union = function(a,b){
    return a.concat(b).uniquelize();
}

补集

Array.complement = function(a,b){
    return Array.minus(Array.union(a,b),Array.intersect(a,b));
}

交集

Array.intersect = function(a,b){
    return a.uniquelize().each(function(o){
        return b.contains(o)?0:null;
    })  
}

转载于:https://www.cnblogs.com/lanxuan826/p/9873702.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值