Mis*_*hko 2 javascript arrays unique
我unique()在Javascript数组中添加了函数:
Array.prototype.unique = function(){
return this.filter(function(item, ind, arr){
return ind == arr.lastIndexOf(item);
});
};
Run Code Online (Sandbox Code Playgroud)
但是当我像这样迭代:
for (i in arr) { ... }
Run Code Online (Sandbox Code Playgroud)
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);}); }
Run Code Online (Sandbox Code Playgroud)
我知道我可以像这样迭代:
for (i = 0; i < arr.length; i++) { ... }
Run Code Online (Sandbox Code Playgroud)
但是,我仍然想知道是否可以Array像这样添加函数和迭代:
for (i in arr) { ... }
Run Code Online (Sandbox Code Playgroud)
?
您可以使该unique属性不可枚举.
Object.defineProperty(Array.prototype, "unique", { enumerable : false,
configurable : true});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1804 次 |
| 最近记录: |