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

2012-05-31 17:57:44 +08:00
 avatasia
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".

多谢。
2588 次点击
所在节点    问与答
6 条回复
darcy
2012-05-31 17:59:39 +08:00
实现object的toString方法。
waterye
2012-05-31 22:48:08 +08:00
代码细节这种问题建议去stackoverflow,好多人抢着答。
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
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
2012-06-01 09:38:36 +08:00
@loddit 这个在我贴的那个算法里还是有问题的。
@cute 凡是代码里涉及到分配内存的操作,肯定效率低,例如这个push
avatasia
2012-06-01 09:51:58 +08:00
@cute
@loddit

好吧,我发现这个问题是由于js不能把非基本类型的object做为key导致的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/37960

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX