$=function(){return{unique1:function(elems){for(vari=0;i<elems.length;++i){// 外层++ifor(varj=i+1;j<elems.length;++j){// 内层j = i +1if(elems[i]===elems[j]){// 判断是否重复的elems.splice(i--,1);// 如果重复,就去掉break;// i-- 与break,保证外层始终从0开始}}}returnelems;},unique2:function(elemsWithId){varobj={};for(vari=0;i<elemsWithId.length;++i){varelem=elemsWithId[i];obj[elem.getAttribute('id')]=obj[elem.getAttribute('id')]||elem;}elemsWithId.length=0;for(varidinobj){elemsWithId.push(obj[id])}returnelemsWithId;}}}();
方法一使用了两重循环,算法复杂度为O(n^2).实现思路比较直观,即遍历数组,看每个元素是否与后面的元素重复,有重复则移除;但是DOM Element数量较多时性能较差,而jQuery中对大量元素进行去除重复的操作很普遍.
方法二将Objct当做HashMap/HashSet来使用,算法复杂度为O(n);遗憾的是JavaScript中无法直接用DOM Element作为Object的key,因此只能将id作为key,然而并非所有的 DOM Element 都是有id 的,所以这种方法并不通用。
varsortOrder,siblingCheck;sortOrder=function(a,b){varal,bl,ap=[],bp=[],aup=a.parentNode,bup=b.parentNode,cur=aup;// If the nodes are siblings (or identical) we can do a quick checkif(aup===bup){returnsiblingCheck(a,b);// If no parents were found then the nodes are disconnected}elseif(!aup){return-1;}elseif(!bup){return1;}// Otherwise they're somewhere else in the tree so we need// to build up a full list of the parentNodes for comparisonwhile(cur){ap.unshift(cur);cur=cur.parentNode;}cur=bup;while(cur){bp.unshift(cur);cur=cur.parentNode;}al=ap.length;bl=bp.length;// Start walking down the tree looking for a discrepancyfor(vari=0;i<al&&i<bl;i++){if(ap[i]!==bp[i]){returnsiblingCheck(ap[i],bp[i]);}}// We ended someplace up the tree so do a sibling checkreturni===al?siblingCheck(a,bp[i],-1):siblingCheck(ap[i],b,1);};siblingCheck=function(a,b,ret){if(a===b){returnret;}varcur=a.nextSibling;while(cur){if(cur===b){return-1;}cur=cur.nextSibling;}return1;};