数组中的唯一值 [英] Unique values in an array
本文介绍了数组中的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我需要确保是唯一的数字数组。我发现code片段下方的互联网上,直到阵列中有一个零它的伟大工程。我发现这个脚本等的这里使容貌几乎完全一样,但它不T失败。
所以对于帮助我学习,有人可以帮助我确定着想那里原型脚本回事?
Array.prototype.getUnique =功能(){
变种O = {},A = [],I,E;
对于(i = 0; E =这个[我],我++){问题o [E] = 1};
对(邻E){a.push(五)};
返回;
}
解决方案
有没有必要使用2 为
循环,只要把一个小小的如果
里面的循环语句
Array.prototype.getUnique =功能(){
变种U = {},A = [];
对于(VAR I = 0,1 = this.length; I<升; ++ I){
如果(u.hasOwnProperty(这由[i])){
继续;
}
a.push(这由[i]);
U [这[一] = 1;
}
返回;
}
I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on SO that looks almost exactly like it, but it doesn't fail.
So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
解决方案
There is no need to use 2 for
loops, just put one small if
statement inside loop
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
这篇关于数组中的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文