indexOf
let arr = [-1, '-1', -1]
let res = []
arr.forEach(item => {
if (res.indexOf(item) === -1) {
res.push(item)
}
})
console.log(res.toString()) // -1,-1
console.log(typeof res[0]) // number
console.log(typeof res[1]) // string
includes
let arr = [-1, '-1', -1]
let res = []
arr.forEach(item => {
if (!res.includes(item)) {
res.push(item)
}
})
console.log(res.toString()) // -1,-1
console.log(typeof res[0]) // number
console.log(typeof res[1]) // string
Set
let arr = [-1, '-1', -1]
let res = []
res = Array.from(new Set(arr))
console.log(res.toString()) // -1,-1
console.log(typeof res[0]) // number
console.log(typeof res[1]) // string
filter
let arr = [-1, '-1', -1]
let res = []
res = arr.filter((item, index) => {
return arr.indexOf(item) === index
})
console.log(res.toString()) // -1,-1
console.log(typeof res[0]) // number
console.log(typeof res[1]) // string
对象属性实现 - 有问题
对象的属性是字符串。这样就会把数字和字符串当成相同的去重掉
let arr = [-1, '-1', -1]
let res = []
let obj = {}
arr.forEach(item => {
if (obj[item] === undefined) {
obj[item] = 1
res.push(item)
}
})
console.log(res.toString()) // -1