It is often used in practical applications to find the complementary set, intersection, difference set, and Union set of the two sets. Below we will share with you the specific implementation code. If you are interested, you can refer to it, hope to help you
The Code is as follows:
/**
* Each is a set iteration function that accepts a function as a parameter and a set of optional parameters.
* This iteration function calculates each element and optional parameter of the Set in sequence using the function, and returns the calculated result set.
{% Example
Script
Var a = [1, 2, 4]. each (function (x) {return x> 2? X: null });
Var B = [1, 2, 4]. each (function (x) {return x <0? X: null });
Alert ();
Alert (B );
Script
%}
* @ Param {Function} fn indicates the Function for iterative determination.
* @ Param more... zero or multiple optional User-Defined parameters
* @ Returns {Array} result set. If no result is returned, an empty set is returned.
*/
Array. prototype. each = function (fn ){
Fn = fn | Function. K;
Var a = [];
Var args = Array. prototype. slice. call (arguments, 1 );
For (var I = 0; I <this. length; I ++ ){
Var res = fn. apply (this, [this [I], I]. concat (args ));
If (res! = Null) a. push (res );
}
Return;
};
/**
* Get an array of non-repeated elements.
* Uniquely define an array
* @ Returns {Array} an Array composed of non-repeating Elements
*/
Array. prototype. uniqustme = function (){
Var ra = new Array ();
For (var I = 0; I <this. length; I ++ ){
If (! Ra. contains (this [I]) {
Ra. push (this [I]);
}
}
Return ra;
};
/**
* Calculate the complementary set of the Two Sets
{% Example
Script
Var a = [1, 2, 4];
Var B = [3, 4, 5, 6];
Alert (Array. complement (a, B ));
Script
%}
* @ Param {Array} a set
* @ Param {Array} B Set B
* @ Returns {Array} is a complementary set of two sets.
*/
Array. complement = function (a, B ){
Return Array. minus (Array. union (a, B), Array. intersect (a, B ));
};
/**
* Intersection of two sets
{% Example
Script
Var a = [1, 2, 4];
Var B = [3, 4, 5, 6];
Alert (Array. intersect (a, B ));
Script
%}
* @ Param {Array} a set
* @ Param {Array} B Set B
* @ Returns {Array} intersection of two sets
*/
Array. intersect = function (a, B ){
Return a. uniquelize (). each (function (o) {return B. contains (o )? O: null });
};
/**
* Calculate the difference set of the Two Sets
{% Example
Script
Var a = [1, 2, 4];
Var B = [3, 4, 5, 6];
Alert (Array. minus (a, B ));
Script
%}
* @ Param {Array} a set
* @ Param {Array} B Set B
* @ Returns {Array} difference set of the Two Sets
*/
Array. minus = function (a, B ){
Return a. uniquelize (). each (function (o) {return B. contains (o )? Null: o });
};
/**
* Calculate the union of two sets
{% Example
Script
Var a = [1, 2, 4];
Var B = [3, 4, 5, 6];
Alert (Array. union (a, B ));
Script
%}
* @ Param {Array} a set
* @ Param {Array} B Set B
* @ Returns {Array} the union of the two Sets
*/
Array. union = function (a, B ){
Return a. concat (B). uniqustme ();
};