<script>
const removeRepeatObj = (arr) => {
for(let i=0,len = arr.length;i<len;i++){
if(typeof arr[i]==='object' && Array.isArray(arr[i])==0 && arr[i] !== null){
arr[i] = JSON.stringify(arr[i]);
}else{}
}
console.log(arr); //test
//基本类型的去重
var res = [];
for(var i=0; i<arr.length; i++) {
if(arr.indexOf(arr[i]) == i) {
res.push(arr[i]);
}
}
//处理对象
console.log(res);//test
for(let j=0;j<res.length;j++){
if(typeof res[j] === 'string' && res[j].indexOf('{')!==-1){
res[j] = JSON.parse(res[j]);
}
}
return res;
}
/* removeRepeatObj([{a:1},{a:1},{a:1,b:2},[1,2,3],[1,2,3],[1,2],[1,{a:2}],[1,{a:2}],3,3,'4',4])*/
方法一
/* function unique(arr) {
var hash = {};
return arr.filter(function (element) {
var key = JSON.stringify(element);
console.log(hash)
return hash[key]?false:(hash[key] = true)
//return hash.hasOwnProperty(key)?false:(hash[key] = true)
//return Object.keys(hash).includes(key)?false:(hash[key] = true)
});
}*/
// console.log(unique([{a:1},{a:1},{a:1,b:2},[1,2,3],[1,2,3],[1,2],[1,{a:2}],[1,{a:2}],3,3,'4']))
/*var obj={a:1,b:2,c:3}
var ar=Object.keys(obj)
console.log(!undefined)*/
//console.log(ar.includes('a'))
方法二
function unique(arr) {
var ret = [];
var tmp = {};
for(var i=0; i<arr.length; i++){
if(!tmp[JSON.stringify(arr[i])]){
tmp[JSON.stringify(arr[i])] = 1;
ret.push(arr[i]);
}
}
console.log(ret)
}
unique( [{a:1},{a:1},{a:1,b:2},[1,2,3],[1,2,3],[1,2],[1,{a:2}],[1,{a:2}],3,3,'4'])
</script>