<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function res(arr){
var temp=[];
? 这里为什么要用两遍sort
arr.sort().sort(function(a,b){
if(a!==b&&temp.indexOf(a)===-1){
temp.push(a)
}
})
return temp;
}
var arr=[1,2,4,4,3,3,1,5,3,0,0,-0,[123],[123],{},{},undefined,undefined,'12','12'];
console.log(arr);
console.log(res(arr))
法二
Array.prototype.unique=function(){
var eee=[];//创建新数组
for(var i=0;i<this.length;i++){ //遍历当前数组
if(eee.indexOf(this[i])===-1){//如果等于-1,那么也是就是新数组中没有一项和当前数组一样
eee.push(this[i])
}
}
return eee;
}
console.log(arr.unique());
</script>
</body>
</html>
为什么使用sort 方法 undifind 和 0 没有呢
第一个sort是默认排序,第二个是是对数组处理,其返回值总是undefined,总等于0情况,相对位置不变。
0没有是因为a!==b&&temp.indexOf(a)===-1,现在0,-0,+0总是恒等的,而排序后0总是在前面,a!==b总是false,在0和1比较为true时,是将1放入数组,所以总是没有0。
undefined则没有参与sort。