第一种方法 不兼容ie6低版本
var arr = [1, 2, 5, 8, 9, 1, 2, 8, 6, 7, 3, 9]; var res = []; for (var i = 0; i < arr.length; i++) { if (res.indexOf(arr[i]) == -1) { res.push(arr[i]); } } console.log(res); // [1, 2, 5, 8, 9, 6, 7, 3]
第二种方法
var arr = [1, 2, 5, 8, 9, 1, 2, 8, 6, 7, 3, 9]; var obj = { 1: true, 2: true, 5: true }; if (!obj[arr[i]]) { res.push(arr[i]); obj[arr[i]] = true; } console.log(obj[i]); // [1, 2, 5, 8, 9, 6, 7, 3]
自定义去重函数
var arr = [1, 2, 5, 8, 9, 1, 2, 8, 6, 7, 3, 9]; function noRepeat(array) { var obj = {}; for (var i = 0; i < array.length; i++) { if (obj[array[i]]) { array[i] = array[array.length -1]; array.length -= 1; i--; continue; } obj[array[i]] = true; } return array; } console.log(noRepeat(arr)); // [1, 2, 5, 8, 9, 6, 7, 3]
第三种方法 ES6数组去重
var arr = [1, 2, 5, 8, 9, 1, 2, 8, 6, 7, 3, 9]; let set = new Set(arr); console.log([...set]); // [1, ,2, 5, 8, 9, 6, 7, 3]