- 数字
const numbers = [2, 3, 4, 4, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 5, 32, 3, 4, 5]
console.log([...new Set(numbers)]); // [2, 3, 4, 5, 6, 7, 32]
- 字符串
const str = ['123', '12', '123', '12', 1, '1', 'a']
console.log([...new Set(str)]); // [ '123', '12', 1, '1', 'a' ]
- 对象(这种情况下,new Set()里面需要接的是strings类型)
const list = [{
name: "张三",
age: 18,
address: "北京"
},
{
name: "李四",
age: 20,
address: "天津"
},
{
name: "张三",
age: 18,
address: "北京"
},
]
let newList = list.map(item => {
return JSON.stringify(item)
})
let res = Array.from(new Set(newList)).map((item) => JSON.parse(item))
console.log(res);
// [
// { name: '张三', age: 18, address: '北京' },
// { name: '李四', age: 20, address: '天津' }
// ]
- 数组,(这种情况下,new Set()里面需要接的是strings类型)
let arr = [
[1],
[2],
[1, [1, [2]]],
[1, [1, [2]]],
[1, [1, 2]],
[1, [1, 2]],
[2]
]
let newArr = arr.map(item => {
return JSON.stringify(item)
})
let res = Array.from(new Set(newArr)).map((item) => JSON.parse(item))
console.log(res);
// [
// [1],
// [2],
// [1, [1, [1, [2]]]],
// [1, [1, 2]]
// ]
4.判断对象
- val != null && val.constructor == Object
let arr = [], obj = {}
console.log(obj != null && obj.constructor == Object); // true
console.log(arr != null && arr.constructor == Object); // false
- Object.prototype.toString.call(val) == '[object Object]'
// Object.prototype.toString.call(val) == '[object Object]'
console.log(Object.prototype.toString.call(obj) == '[object Object]'); //true
console.log(Object.prototype.toString.call(arr) == '[object Object]'); //false
5.判断空数组
const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;
const isNotEmpty = (arr) => JSON.stringify(arr) === '{}';
6.判断空对象
const isEmpty = (obj) => JSON.stringify(obj) === '{}';