方法一:
var arr = [1,1,2,5,5,8,3,8,3];
var result = [];
for(var i = 0;i < arr.length;i++){
var value = arr[i];
if(result.indexOf(value) == -1){//在数组result中找元素是value的索引值,没找到返回值为-1,把该元素添加到result里
result.push(value);
}
}
console.log(result);
结果 : [1, 2, 5, 8, 3]
方法二:不但可以去重,还会进行排序
var arr = [1,2,8,5,3,5,2,7,9,6,3,6,3,5,3,5];
var result = {};
for(var i = 0;i < arr.length;i++){
var value = arr[i];
result[value] = 1;
}
console.log(Object.keys(result));
结果: ["1", "2", "3", "5", "6", "7", "8", "9"]
方法三:ES6新出的set方法,代码超级简短
var arr = [1,2,4,5,3,2,2];//需要去重的数组
var set = new Set(arr); //{1,2,4,5,3}
var newArr= Array.from(set); //再把set转化为array
console.log(newArr,set); //[1,2,4,5,3]
网友评论