V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
avatasia
V2EX  ›  问与答

javascript 数组去重算法问题,求高手解答

  •  
  •   avatasia · 2012-05-31 17:57:44 +08:00 · 2581 次点击
    这是一个创建于 4362 天前的主题,其中的信息可能已经有所发展或是发生改变。
    if(!Array.prototype.unique){
    Array.prototype.unique = function() {
    var temp = {}, len = this.length;
    for(var i=0; i < len; i++) {
    var tmp = this[i];
    if(!temp.hasOwnProperty(tmp)) {
    temp[this[i]] = "hoho";
    }
    }
    this.length = 0;
    len = 0;
    for(var i in temp) {
    this[len++] = i;
    }
    return this;
    }
    }

    如果数组是一个object数组,例如[{a:1,b:2}, {a:1, b:2}],
    在temp[this[i]]="hoho";这里就变成了 temp["[object object]"] = "hoho"; 怎么样才能实现temp[{a:1, b:2}] = "hoho".

    多谢。
    6 条回复    1970-01-01 08:00:00 +08:00
    darcy
        1
    darcy  
       2012-05-31 17:59:39 +08:00
    实现object的toString方法。
    waterye
        2
    waterye  
       2012-05-31 22:48:08 +08:00
    代码细节这种问题建议去stackoverflow,好多人抢着答。
    cute
        3
    cute  
       2012-05-31 23:58:42 +08:00
    @avatasia
    @waterye
    @darcy

    一个简单的序列化方法,楼主测试下一下。


    function hashify(item){
    var temp = [];
    for (var k in item){
    if(item.hasOwnProperty(k)) {
    temp.push([k,item[k]!==null && item[k].toString()=='[object object]'?hashify(item[k]):item[k]]);
    }
    }
    temp = temp.sort(function(a,b){
    return a[0] > b[0] ? 1 : -1;
    });
    return temp.join("\n");
    }

    alert(hashify({a:1,c:5,b:2}));
    alert(hashify({a:1,c:5,b:2})==hashify({a:1,b:2,c:5}));
    alert(hashify({a:1,c:{b:2}})==hashify({c:{b:2},a:1}));
    loddit
        4
    loddit  
       2012-06-01 00:14:23 +08:00
    我这里测试只把 this[i] 改成函数里的 tmp ,似乎就没有问题,为了方便我直接把属性都加 Object 上了。
    写了一阵coffee以后,看js有很吃力呀。

    > Object.prototype.test = function() {
    var temp = {};
    len = this.length;
    for(var i=0; i < len; i++) {
    var tmp = this[i];
    if(!temp.hasOwnProperty(tmp)) {console.log(tmp);
    temp[tmp] = "hoho";
    }
    }
    Object.scene = temp
    }
    > [{a:1,b:2}, {a:1, b:2}].test()
    > Object.scene[{a:1,b:2}]
    display => "hoho"
    avatasia
        5
    avatasia  
    OP
       2012-06-01 09:38:36 +08:00
    @loddit 这个在我贴的那个算法里还是有问题的。
    @cute 凡是代码里涉及到分配内存的操作,肯定效率低,例如这个push
    avatasia
        6
    avatasia  
    OP
       2012-06-01 09:51:58 +08:00
    @cute
    @loddit

    好吧,我发现这个问题是由于js不能把非基本类型的object做为key导致的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4996 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 09:49 · PVG 17:49 · LAX 02:49 · JFK 05:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.