之前提过一个想法,数组中有多种数据类型的时候怎么进行数组去重,今天利用下班时间写了个,https://github.com/GeekFE/arrUniq/blob/master/arrUniq.js,直接上链接,大家帮忙瞅瞅!写的不好的地方还请担待!
声明下,没有用到ES6,为什么大家都懂得!
var arr = [1,2,2,{a:1},{a:1}, [1,2,3], [1,2,3], a, b];
console.log(arr.arrUniq());
function a(){
console.log(1111);
}
function b(){
console.log(1111);
}
控制台最后会输出[ 1,2,{ a: 1 },[ 1, 2, 3 ],[ 1, 2, 3 ],[Function: a],[Function: b] ]
对于函数的判断的话,个人认为应该判断函数体里的内容,而不是整个fun.toString()
的内容
这里还有一个问题就是,对与数组不起作用,原因在于if(temp == typeArr['arr']) arrVal.arrUniq();
这递归调用=。=(你确定有用?)
最后贴上我的一个写法
function Set(){
this.dataStore = [];
}
Set.prototype.find = function(element){
return this.dataStore.indexOf(element);
};
Set.prototype.add = function(element){
var stringifyElement = this.toString(element);
if(this.find(stringifyElement) == -1){
this.dataStore.push(stringifyElement);
return true;
}else{
return false;
}
};
Set.prototype.toString = function(element){
var type = Object.prototype.toString(element);
switch(type){
case '[object Object]':
return JSON.stringify(element);
break;
case '[object Function]':
return this.funToString(element);
break;
case '[object Array]':
return element.toString();
default:
return element;
}
};
Set.prototype.funToString = function(fun){
var funRe = /^\s*function\s*.*\(.*\).*\{([\s\S]+)\}$/g,
funEnt = /(\u3000|\s|\t|\n)*/gi,
funBody = funRe.exec(fun.toString())[1];
return funBody.replace(funEnt, '');//去掉函数体内的所有空格,包括\n,\t
};
Array.prototype.uqiue = function(){
var set = new Set(),
arr = [];
arr = this.filter(function(item){
return set.add(item);
});
return arr;
};
var arr = [1,2,2,{a:1},{a:1}, [1,2,3], [1,2,3], a, b];
console.log(arr.uqiue()); //[ 1, 2, { a: 1 }, [ 1, 2, 3 ], [Function: a] ]
function a(){
console.log(1111);
}
function b(){
console.log(1111);
}
核心思想是通过set这个数据结构来次过滤(自己造个Set小轮子哈~)
javascript
Array.prototype.unique = function() { return this.filter(function(value,key,arr){ return arr.indexOf(value)>=key; }) } [1,2,2,3].unique();//[1,2,3] but:[1,2,'2',3].unique();//[1,2,3]
我不是来挑毛病的,我是来挑刺的:
javascript
NaN != NaN
var array = [1, 2, 3, 3, 2];
var uniqArray = [...new Set(array)];
Array.prototype.unique = function() {
var json = {};
var res = [];
for(var i = 0;i < this.length;i++) {
if(!json[this[i]]) {
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
var a = [1,2,3,3,2,1,4,4,0,7];
console.log(a.unique());