js数组去除重复方法添加
很多校招题是没有严格的标准答案的,只有知识点,只要几个关键点能答上来,不管程序是否真的能跑通,都可以拿分的。比如最常见的一道题:
试题:
有这样一个数组,成员都是数字,例如
var a = [1,2,3,4,5,2,3,4,6,7,8];
请实现a.distinct()方法,用来给数组a去掉重复值,要求对Array的原型进行扩展方法,并尽可能做到效率最优。
考察点:
1,考察应试者是否理解原型链
2,考察应试者是否由意识的控制算法的时间复杂度,了解应试者对专业课知识的掌握程度
3,考察应试者对js数组函数的了解程度
答案1:
Array.prototype.distinct?=?function(){???? var?a?=?[],b=[],oa?=?this.concat();// 将原来数据赋值给oa数组???? for(var?i?=?1;i<oa.length;i++){???????? for(var?j?=?0;j<i;j++){???????????? if(b.indexOf(j)>-1)continue;//如过下表j在数组b中跳出当前循环 ??????????? if(oa[j]?==?oa[?i]){ ????????????? b.push(j);???????????? }???????? }???? }???? this.splice(0,this.length);//将原数组清空成为空数组???? for(var?i?=?0;i<oa.length;i++){???????? if(b.indexOf(i)>-1) continue;?????? this.push(oa[i?]);???? }???? return?this;?};答案2:
Array.prototype.distinct?=?function(){???? for(var?i?=?0;i<this.length;i++){???????? var?n?=?this[i?];???????? this.splice(i,1,null);???????? if(this.indexOf(n)?<?0){???????????? this.splice(i,1,n);//不存在重复???????? }else{???????????? this.splice(i,1);//存在重复???????? }???? }???? return?this;?};答案3:
Array.prototype.distinct?=?function(){???? var?self?=?this;???? var?_a?=?this.concat().sort();???? _a.sort(function(a,b){???????? if(a?==?b){???????????? var?n?=?self.indexOf(a);???????????? self.splice(n,1);???????? }???? });???? return?self;?};得分点:
1,应试者起码应该自觉通过Array.prototype.distince来实现函数,若没有这样做,则扣分50%
2,应试者起码会给出答案1,得分30%,如果没有使用splice和concate,扣分20%
3,给出答案2的,得分80%,算法复杂度控制在O(n)
?其他方法:
<SCRIPT LANGUAGE="JavaScript">
Array.prototype.deleteEle=function(){?? ?var arr=this,o={},newArr=[],i,n;?? ?for( i=0;i<arr.length;i++){?? ? ? ?n=arr[i]+typeof(arr[i]);//如果不需要类型判断,直接将后面的去掉即可?? ? ? ?if(typeof(o[n])==="undefined"){?? ? ? ? ? ?newArr[newArr.length]=arr[i]?? ? ? ? ? ?o[n]=1;//缓存?? ? ? ?}?? ?}?? ?return newArr;}var x= [1,2,3,4,5,2,3,4,6,7,8];document.write('原始数组:'+x);document.write("<br />");document.write('去重复后:'+x.deleteEle());?Array.prototype.distinct=function(){var a=[],b=[];for(var prop in this){?? var d = this[prop];?? if (d===a[prop]) continue; //防止循环到prototype?? if (b[d]!=1){?? ?a.push(d);?? ?b[d]=1;?? }}return a;}var x=['a','b','c','d','b','a','e','a','b','c','d','b','a','e'];document.write('原始数组:'+x);document.write("<br />");document.write('去重复后:'+x.distinct());?</script>