2012-03-18 61 views
2

我加入unique()功能JavaScript数组:的Javascript “唯一的()” 函数

Array.prototype.unique = function(){ 
    return this.filter(function(item, ind, arr){ 
    return ind == arr.lastIndexOf(item); 
    }); 
}; 

但是当我重复这样的:

for (i in arr) { ... } 

i变得unique还有:

var arr = [1, 2, 1]; 
for (i in arr) { 
    console.log(i + " ===> " + arr[i]); 
} 

// 0 ===> 1 
// 1 ===> 2 
// 2 ===> 1 
// unique ===> function() { return this.filter(function (item, ind, arr) {return ind == arr.lastIndexOf(item);}); } 

我知道我可以这样迭代:

for (i = 0; i < arr.length; i++) { ... } 

但是,我仍然不知道,如果有可能的功能添加到Array并重复这样的:

for (i in arr) { ... } 

+4

你不应该使用一个数组http://stackoverflow.com/a/6974628/575527操作时在 – Joseph 2012-03-18 11:26:16

+0

相似:使用Javascript定制Array.prototype与-in循环干扰(HTTP:/ /stackoverflow.com/questions/1529593/javascript-custom-array-prototype-in​​terfering-with-for-in-loops),[JavaScript“For ... in”with Arrays](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) – minopret 2012-03-18 11:36:29

回答

5

您可以使unique属性不可枚举。

Object.defineProperty(Array.prototype, "unique", { enumerable : false, 
                configurable : true}); 
+2

这里是一个[示例](http://jsfiddle.net/94v4w/)。 – scessor 2012-03-18 11:43:22