数组去重
一:
var arr = [1,7,8,9,7,8,0,0,0,0,9,1,1,2,3,4,2,2,3,4,5,10,10,10,"a","b","a","b","a","b"]
function arrayUnique(arr) {
var obj = {};
var arrFinal = [];
for(var i = 0, len = arr.length; i < len; i++) {
if(!obj[arr[i]]) {
obj[arr[i]] = "array";
arrFinal.push(arr[i])
}
}
return arrFinal;
}
var arr1 = arrayUnique(arr);
console.log(arr1);
二:
通过原型链
var arr = [1,7,8,9,7,8,0,0,0,0,9,1,1,2,3,4,2,2,3,4,5,10,10,10,"a","b","a","b","a","b"]
Array.prototype.unique = function() {
var obj = {};
var arrFinal = [];
for(var i = 0, len = this.length; i < len; i++) {
if(!obj[this[i]]) {
obj[this[i]] = "array";
arrFinal.push(this[i])
}
}
return arrFinal;
}
var arr2 = arr.unique();
console.log(arr2)
两个代码,一个是通过原型链可像操作数组一样使用;一个是一个方法传参数调用。都是通过对象的特性,把数组转成对象内的属性值,相同的属性值会互相覆盖,这样相同的数组值就会筛选出来了。
如图:
字符串去重
var str = "aabbccddeeffgg1122";
function strFn(str) {
var obj = {};
var strFinal = "";
for (i in str) {
if(!obj[str[i]]) {
obj[str[i]] = "abc";
strFinal += str[i]
}
}
return strFinal;
}
strFn(str)