一个JavaScript笔试题目
问题描述:给Array本地对象,增加一个原型方法,删除数组中重复的条目,返回一个包含被删除的重复条目数组。
代码:
View Code
1 <html>
2 <head>
3 </head>
4 <body>
5 <script type="text/javascript">
6
7 Array.prototype.distinct = function(){
8 var b={},c,i=0,l=this.length;
9 for(;i<l;i++)
10 {
11 c = this.shift();
12 c in b ?b[c]++:b[c]=0;
13 }
14 for(j in b)
15 {
16 if(b[j]>0){
17 this.push(j);
18 }
19 }
20 return this;
21 }
22 var colors =new Array("red","red","blue","blue","blue","white","black","blue",1,1,2);
23 alert(colors.distinct());
24 </script>
25 </body>
26 </html>
利用对象的存储数组中取出来的项,每一个项都当作对象的一个属性,属性值为重复条目的重复次数。

浙公网安备 33010602011771号