最近在小一个小程序项目,突然发现 javscript 对数组支持不是很好,连这些基本的功能,都还要自己封装.网上查了下,再结合自己的想法,封装了一下,代码如下.
//数组交集 Array.prototype.intersect = function(){ let mine = this.concat(); for (var i = 0; i < arguments.length; i++) { mine.map(function (value, index) { if (!this.includes(value)) delete mine[index]; }, arguments[i]); } return mine.filter(v => v); }; //数组差集:返回在当前数组中,但不在其他数组中的元素 Array.prototype.minus = function(){ let mine = this.concat(); for (var i = 0; i < arguments.length; i++) { mine.map(function (value, index) { if (this.includes(value)) delete mine[index]; }, arguments[i]); } return mine.filter(v => v); }; //过滤数组重复元素 Array.prototype.unique = function(){ let result = []; this.map(function (value, index) { if (!this.includes(value)) this.push(value); }, result); return result; }; //数组并集 Array.prototype.union = function(){ let result = this.concat(); for (var i = 0; i < arguments.length; i++) { arguments[i].map(function (value, index) { if (!this.includes(value)) this.push(value); }, result); } return result; }; [1, 2, 3, 2, 1].unique(); [1, 2, 3].intersect([1, 2, 8], [1, 2, 6], [1, 2, 3]); [1, 2, 3].minus(["aaaa", 2], [ "cccc", 1]); [1, 2, 3].union(["Robin", "aaaa", "bbbb"], ["aaaa", "cccc"]);