看论坛上的一个帖子有感

来源:互联网 发布:09淘宝店 编辑:程序博客网 时间:2024/04/19 05:41

帖子地址:http://www.iteye.com/topic/1118420

简要说明一下,就是写一个javascript的方法(扩展Array的方法),用于消除array的重复元素

一般方法,复杂度为o(n^2)

       Array.prototype.distinct = function() {        var ret = [];        for (var i = 0; i < this.length; i++) {         for (var j = i+1; j < this.length;) {             if (this[i].id === this[j].id) {                 ret.push(this.splice(j, 1)[0]);             } else {                 j++;             }         }        }        return ret;}

回帖中,一个人提出了另外的一个办法:
Array.prototype.distinct = function(field) {  var set = {},    hasField = typeof(field)!='undefined';  for(var i=this.length-1; i>=0; i--){    var obj = this[i],      cacheKey = hasField ? obj[field] : obj;    if(cacheKey in set){      this.splice(i, 1);      continue;    }else{      set[cacheKey] = null;    }  }}//testvar a = [{id:1, name:'aaa'}, {id:2, name:'bbb'}, {id:1, name:'ccc'}];a.distinct('id');var b = [1,2,3,'a','b',2,'b',3];b.distinct();console.debug(a);console.debug(b);

效率上有很大的提升,看来,每一段小代码都有很多值得思考的地方,作为一个程序员,对自己的代码需要有严格的要求。


原创粉丝点击