学习笔记。。。积累!!

合抱之木,生于毫末。九层之台,起于累土。千里之行,始于足下

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

晚上无事,偶然看到这么个小测试,拿来写一写,希望大家提建议;

直接上代码:

 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认为相同

注意:

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

2、使用类型判断,如果当前数组值做为对象键,所对应的对象值类型与当前值类型一致,则可以根据参数(isStirct严格模式)决定是否去重,true表示严格,对于字符为22,或数字为22都认为一样,否则保留

看了一下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'认为是不同

 

posted on 2014-03-03 23:17  gaojun  阅读(6252)  评论(0编辑  收藏  举报