数组去重在ES6可以通过Set数据结构来实现
let arr=[null,null,undefined,undefined,NaN,NaN,Infinity,Infinity,'','',,1,'1']
console.log([...new Set(arr)])//[null, undefined, NaN, Infinity, "",1,'1']
使用filter方法:
let arr=[null,null,undefined,undefined,NaN,NaN,Infinity,Infinity,'','',1,'1']
function outRepetition(){
return arr.filter(function(v,i,arr){return arr.indexOf(v)===i})
}
console.info(outRepetition(arr))//[null, undefined, Infinity, "", 1, "1"]
显然,上面的方法会丢失值为NaN的项,所以,进一步进行完善
let arr=[null,null,undefined,undefined,NaN,NaN,Infinity,Infinity,'','',1,'1',1]
function outRepetition(arr){
var brr=arr.filter(function(v,i,arr){return arr.indexOf(v)===i})
let bool=arr.some(function(v){return isNaN(v)})
bool&&brr.push(NaN)
return brr
}
console.info(outRepetition(arr))//[null, undefined, Infinity, "", 1, "1", NaN]
哈希方法:
var arr = [null, null, undefined, undefined, NaN, NaN, Infinity, Infinity, '', '', 1, '1', 1]
if(!Array.prototype.unique) {
Array.prototype.unique = function() {
var hash = {},
arr = [],
type, item;
for(var l = this.length, i = 0; i < l; i++) {
item = this[i];
type = Object.prototype.toString.call(item);
if(!hash[item + type]) {
hash[item + type] = true;
arr.push(item);
}
}
return arr;
}
}
arr = arr.unique();
console.log(arr);
至于字符串去重,可以通过数组去重来实现,下面是一个通过正则来实现字符串去重的方法:
var str='aabb ca bAb'
str=str.replace(/(.)(?=.*\1)/g, '')
console.log(str)