1. 程式人生 > >去掉陣列中重複的數字

去掉陣列中重複的數字

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//var a = [1,2,3,4,5,1,2,3,4,5,6];
//去掉陣列中重複的數字,返回:1,2,3,4,5;
var a = [1,2,3,4,5,1,2,3,4,5,6];
a.sort(function (n,m) {
return n - m;
});//a陣列的值從小到大排序;
for (var i = 0;i < a.length;i++){
if (a[i] === a[i + 1]){//如果(第i個)等於(第i個加1);
a.splice(i,1);//刪除(第i個,刪除的個數為1);
i--;//返回去重新再查詢一次;
}
}
alert(a);
</script>
</head>
<body>

</body>
</html>