方法一:利用indexOf
let arr = [1, 2, '1', 1, 2, 3, 4, 4, 5, 3];function arrRepeat(arr) { let newArr = [] for(let i = 0; i < arr.length; i++) { if(newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]) } } console.log(newArr)return newArr}arrRepeat(arr)
方法二:利用 hasOwnProperty
function arrRepeat(arr) { let obj = {}; let newArray = []; for(let i = 0; i < arr.length; i++) { if(!obj.hasOwnProperty(arr[i])) { obj[arr[i]] = i; newArray.push(arr[i]); } } return newArray}console.log(arrRepeat([1,2,1,3,5,'哈','哈',3,6,'q','a','q','a'])) //[1, 2, 3, 5, "哈", 6, "q", "a"]
方法三:利用ES6的set (一行代码数组去重)
Set数据结构,它类似于数组,其成员的值都是唯一的。
利用Array.from将Set结构转换成数组
let array = Array.from(new Set([1, 1, 1, 2, 3, 2, 4]));
Set数据结构
let arr = [1,2,3,3];let resultarr = [...new Set(arr)]; console.log(resultarr); //[1,2,3]
方法四: 双循环
双层循环,外层循环元素,内层循环时比较值如果有相同的值则跳过,不相同则push进数组function arrRepeat(arr){ let result = [], i, j, len = arr.length; for(i = 0; i < len; i++){ for(j = i + 1; j < len; j++){ if(arr[i] === arr[j]){ j = ++i; } } result.push(arr[i]); } return result;}console.log(arrRepeat([1,2,1,3,5,'哈','哈',3,6,'q','a','q','a'])) // [2, 1, 5, "哈", 3, 6, "q", "a"]