javascript 数组去重 unique

晚上无事,偶然看到这么个小测试,拿来写一写,但愿你们提建议;数组

直接上代码:测试

 1 Array.prototype.unique = function (isStrict) {  2     if (this.length < 2)  3         return [this[0]] || [];  4     var tempObj = {}, newArr = [];  5     for (var i = 0; i < this.length; i++) {  6         var v = this[i];  7         var condition = isStrict ? (typeof tempObj[v] != typeof v) : false;  8         if ((typeof tempObj[v] == "undefined") || condition) {  9             tempObj[v] = v; 10  newArr.push(v); 11  } 12  } 13     return newArr; 14 }

验证:
var arr = ["9", 9, 1, 3, 8, 7, 7, 6, 6, 5, 7, 8, 8, 7, 4, 3, 1, 22, 22, 'a', 'a','bcd', 'abc', 'bcd'];
var newArr = arr.unique(true);
alert(newArr.join(","));//严格模式:9,9,1,3,8,7,6,5,4,22,a,bcd,abc,将其中"9",9认为不一样

var newArr = arr.unique();
alert(newArr.join(","));//普通模式:9,1,3,8,7,6,5,4,22,a,bcd,abc,将其中"9",9认为相同

注意:this

一、使用临时对象tempObj,将数组的值做为对象的键值,遍历数组时对当前值根据对象键值判断,不存在就将这个数组的值push到新数组中。提升效率spa

二、使用类型判断,若是当前数组值作为对象键,所对应的对象值类型与当前值类型一致,则能够根据参数(isStirct严格模式)决定是否去重,true表示严格,对于字符为22,或数字为22都认为同样,不然保留prototype

看了一下JavaScript高级程序设计中关于数组的操做,又想到种更简单的去重方法,代码以下:设计

 1 Array.prototype.unique = function () {  2     var newArr = [];  3     for (var i = 0; i < this.length; i++) {  4         if (newArr.indexOf(this[i]) == -1) {  5             newArr.push(this[i]);  6  }  7  }  8     return newArr;  9 } 10 var arr = ['a','b',1,4,5,8,4,3,1,'a','1']; 11 alert(arr.unique());//a,b,1,4,5,8,3,1  indexOf默认调用===,所以将1与'1'认为是不一样
相关文章
相关标签/搜索