/*** each是一個集合迭代函數,它接受一個函數作為參數和一組可選的參數* 這個迭代函數依次將集合的每一個元素和選擇性參數用函數進行計算,並將計算得的結果集返回{%example<script> var a = [1,2,3,4].each(function(x){return x > 2 ? x : null}); var b = [1,2,3,4].each(function(x){return x < 0 ? x : null}); alert(a); alert(b);</script>%}* @param {Function} fn 進行迭代判定的函數* @param more ... 零個或多個可選的使用者自訂參數* @returns {Array} 結果集,如果沒有結果,返回空集*/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 a;};/*** 得到一個數組不重複的元素集合<br/>* 唯一化一個數組* @returns {Array} 由不重複元素構成的數組*/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;};/*** 求兩個集合的補集{%example<script> var a = [1,2,3,4]; var b = [3,4,5,6]; alert(Array.complement(a,b));</script>%}* @param {Array} a 集合A* @param {Array} b 集合B* @returns {Array} 兩個集合的補集*/Array.complement = function(a, b){ return Array.minus(Array.union(a, b),Array.intersect(a, b));};/*** 求兩個集合的交集{%example<script> var a = [1,2,3,4]; var b = [3,4,5,6]; alert(Array.intersect(a,b));</script>%}* @param {Array} a 集合A* @param {Array} b 集合B* @returns {Array} 兩個集合的交集*/Array.intersect = function(a, b){ return a.uniquelize().each(function(o){return b.contains(o) ? o : null});};/*** 求兩個集合的差集{%example<script> var a = [1,2,3,4]; var b = [3,4,5,6]; alert(Array.minus(a,b));</script>%}* @param {Array} a 集合A* @param {Array} b 集合B* @returns {Array} 兩個集合的差集*/Array.minus = function(a, b){ return a.uniquelize().each(function(o){return b.contains(o) ? null : o});};/*** 求兩個集合的並集{%example<script> var a = [1,2,3,4]; var b = [3,4,5,6]; alert(Array.union(a,b));</script>%}* @param {Array} a 集合A* @param {Array} b 集合B* @returns {Array} 兩個集合的並集*/Array.union = function(a, b){ return a.concat(b).uniquelize();};