JS数组去重与字符串去重
// 数组去重
var arr = [0, 0, 1, 1, 1, 2, 2, 2, 'a', 'a']
Array.protoyepe.unique = function (){
var temp = {};
var newArr = [];
for( var i = 0 ; i < this.length; i++){
// 通过创建一个空对象去接收遍历的结果,通过 对象的一个方法hasOwnProperty来判断对象是否有该属性,
// 如果有不执行条件里面的语句,没有则在temp对象中添加当前属性 , 并将当前的值push到数组里面
if(!temp.hasOwnProperty(this[i])){
temp[this[i] = this[i];
newArr.push(this.[i])
}
}
return newArr // 将新数组return出去
}
===============================================================================================
// 字符串去重
var str = '11223344455aabb'
String.prototype.unique = function(){
var temp = {};
var newStr = '';
for(var i = 0; i < this,lenght; i++){
if(!temp.hasOwnProperty(this.[i]){
temp[this[i]] = this[i];
newStr += this[i]
}
}
return newStr;
}

浙公网安备 33010602011771号