方法一:遍历数组,建立新数组,利用indexOf判断是否存在于新数组中,不存在则push到新数组,最后返回新数组
var arr = [1,2,3,1,43,12,12,1];
var ret = [];
for (var i = 0, j = arr.length; i < j; i++) {
if (ret.indexOf(arr[i]) === -1) {
ret.push(arr[i]);
}
}
console.log(ret);
VM29294:10 [1, 2, 3, 43, 12]
方法二:遍历数组,利用object对象保存数组值,判断数组值是否已经保存在object中,未保存则push到新数组并用object[arrayItem]=1的方式记录保存
var ar = [1,2,3,1,43,12,12,1];
var tmp = {},
ret = [];
for (var i = 0, j = ar.length; i < j; i++) {
if (!tmp[ar[i]]) {
tmp[ar[i]] = 1;
ret.push(ar[i]);
}
}
console.log(ret);
方法三:数组下标判断法, 遍历数组,利用indexOf判断元素的值是否与当前索引相等,如相等则加入
var ar = [1,2,3,1,43,12,12,1];
var ret = [];
ar.forEach(function(e, i, ar) {
if (ar.indexOf(e) === i) {
ret.push(e);
}
});
console.log(ret);
VM82566:13 [1, 2, 3, 43, 12]
方法四:数组先排序, 然后比较俩数组前后进行去重
var ar = [1,2,3,1,43,12,12,1];
ret = [];
ar.sort();
var end = ar[0];
ret.push(ar[0]);
for (var i = 1; i < ar.length; i++) {
if (ar[i] != end) {
ret.push(ar[i]);
end = ar[i];
}
}
console.log(ret);
VM83040:19 [1, 12, 2, 3, 43]