1.使用filter结合indexOf
const array = [5, 4, 7, 8, 9, 2, 7, 5]
const unque6 = (array) => {
return array.filter((item, idx, arr) => arr.indexOf(item) === idx)
}
2.使用new Set
const unique = (arr) => {
return [...new Set(arr)]
}
3.使用includes
const unique = (arr) => {
const result = []
for (let j = 0; j < arr.length; j++) {
if (!result.includes(arr[j])) {
return result.push(arr[j])
}
}
return result
}
4.利用对象属性名的唯一性来保证不重复
const unique = (arr) => {
const result = {}
for (let i = 0; i < arr.length; i++) {
if (!result[arr[i]]) {
result[arr[i]] = true
}
}
return Object.keys(result)
}