本文介紹了JS數組交集、并集、差集,分享給大家,具體如下:
由于下面會用到ES5的方法,低版本會存在兼容,先應添加對應的polyfill
Array.prototype.indexOf = Array.prototype.indexOf || function (searchElement, fromIndex) {  var index = -1;  fromIndex = fromIndex * 1 || 0;  for (var k = 0, length = this.length; k < length; k++) {    if (k >= fromIndex && this[k] === searchElement) {      index = k;      break;    }  }  return index;};Array.prototype.filter = Array.prototype.filter || function (fn, context) {  var arr = [];  if (typeof fn === "function") {    for (var k = 0, length = this.length; k < length; k++) {      fn.call(context, this[k], k, this) && arr.push(this[k]);    }  }  return arr;};依賴數組去重方法:
// 數組去重Array.prototype.unique = function() {  var n = {}, r = [];  for (var i = 0; i < this.length; i++) {    if (!n[this[i]]) {      n[this[i]] = true;      r.push(this[i]);     }  }  return r;}交集
交集元素由既屬于集合A又屬于集合B的元素組成
Array.intersect = function(arr1, arr2) {  if(Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {    return arr1.filter(function(v){      return arr2.indexOf(v)!==-1     })   }}// 使用方式Array.intersect([1,2,3,4], [3,4,5,6]); // [3,4]并集
并集元素由集合A和集合B中所有元素去重組成
Array.union = function(arr1, arr2) {  if(Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {    return arr1.concat(arr2).unique()  }}// 使用方式Array.union([1,2,3,4], [1,3,4,5,6]); // [1,2,3,4,5,6]差集
A的差集:屬于A集合不屬于B集合的元素
B的差集:屬于B集合不屬于A集合的元素
Array.prototype.minus = function(arr) {  if(Object.prototype.toString.call(arr) === "[object Array]") {    var interArr = Array.intersect(this, arr);// 交集數組    return this.filter(function(v){      return interArr.indexOf(v) === -1    })  }}// 使用方式var arr = [1,2,3,4];arr.minus([2,4]); // [1,3]以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答