<!DOCTYPE html>
<html>
<head>
<title>数组去重</title>
</head>
<body>
<script type="text/javascript">
var arr = [1,2,3,2,1,4,6,8,4,6,9];
function unique(arr){
var arr1 = [];//定义一个空数组
for(var i=0;i<arr.length;i++){
//使用ndexOf方法当值为-1时,表明
//arr[i]的某个值在arr1这个数组中不存在
if( arr1.indexOf(arr[i]) == -1 ){
//然后把值push到arr1数组中
arr1.push(arr[i]);
}
console.log(arr1);//[1, 2, 3, 4, 6, 8, 9]
}
}
unique(arr);
</script>
</body>
</html>
-----------------------------------------------------------
<script type="text/javascript">
var arr = [1,2,3,2,1,4,6,8,4,6,9];
var arr1 = [];//定义一个空数组
for(var i=0;i<arr.length;i++){
//使用ndexOf方法当值为-1时,表明
//arr[i]的某个值在arr1这个数组中不存在
if( arr1.indexOf(arr[i]) == -1 ){
//然后把值push到arr1数组中
arr1.push(arr[i]);
}
}
console.log(arr1) //[1, 2, 3, 4, 6, 8, 9]
</script>
网友评论