# 利用object的key唯一性删除数组重复项
# uniq.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
var arr=[12,34,22,34,55,90,66,12,90,9,12,33,22]
//将数组转换为object,数组的元素转换为Object的key
function toObject(arr){
var obj={}
for (var i = arr.length - 1; i >= 0; i--) {
obj[arr[i]]=true
}
return obj
}
//obj的key还原为arr的元素
function toArray(obj) {
var arr=[]
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
arr.push(attr)
}
}
return arr
}
//删除重复项的代码
function uniq(arr){
return toArray(toObject(arr))
}
var u=uniq(arr)
console.log('删除重复前:'+arr)
console.log('删除重复后:'+u)
</script>
</head>
<body>
</body>
</html>
# result:
删除重复前:12,34,22,34,55,90,66,12,90,9,12,33,22
删除重复后:9,12,22,33,34,55,66,90