代码
<script type="text/javascript">
Array.prototype.distinct = function(){
var $ = this;
var o1 = {}; //存放去重复值
var o2 = {}; //存放重复值
var o3 = []; //存放重复值
var o; //数组单个变量
for(var i=0;o = $[i];i++){
if(o in o1){
if(!(o in o2)) o2[o] = o;
delete $[i];
}else{
o1[o] = o;
}
}
$.length = 0; //清空原数组
for(o in o1){
$.push(o);
}
for(o in o2){
o3.push(o);
}
return o3;
}
var a = [2,2,2,3,3,3,4,4,5,6,7,7];
alert("原数组:" + a);
alert("有重复的元素是:" + a.distinct()); //2,3,4,7
alert("整理后的数组是:" + a); //2,3,4,5.6,6
alert("整理后的长度是:" + a.length) //6
</script>
Array.prototype.distinct = function(){
var $ = this;
var o1 = {}; //存放去重复值
var o2 = {}; //存放重复值
var o3 = []; //存放重复值
var o; //数组单个变量
for(var i=0;o = $[i];i++){
if(o in o1){
if(!(o in o2)) o2[o] = o;
delete $[i];
}else{
o1[o] = o;
}
}
$.length = 0; //清空原数组
for(o in o1){
$.push(o);
}
for(o in o2){
o3.push(o);
}
return o3;
}
var a = [2,2,2,3,3,3,4,4,5,6,7,7];
alert("原数组:" + a);
alert("有重复的元素是:" + a.distinct()); //2,3,4,7
alert("整理后的数组是:" + a); //2,3,4,5.6,6
alert("整理后的长度是:" + a.length) //6
</script>
一个同行对上述程序代码不解,主要是不理解下面这段代码:
for(var i=0;o = $[i];i++){
if(o in o1){
if(!(o in o2)) o2[o] = o;
delete $[i];
}else{
o1[o] = o;
}
}
if(o in o1){
if(!(o in o2)) o2[o] = o;
delete $[i];
}else{
o1[o] = o;
}
}
最后一起研究,讨论如下: