wbr*_*ady 12 javascript function
我想在Array.prototype和Object.prototype上定义辅助方法.我目前的计划是做类似的事情:
Array.prototype.find = function(testFun) {
// code to find element in array
};
Run Code Online (Sandbox Code Playgroud)
所以我可以这样做:
var arr = [1, 2, 3];
var found = arr.find(function(el) { return el > 2; });
Run Code Online (Sandbox Code Playgroud)
它工作正常,但如果我在循环中循环数组,for in方法显示为值:
for (var prop in arr) { console.log(prop); }
// prints out:
// 1
// 2
// 3
// find
Run Code Online (Sandbox Code Playgroud)
这将搞砸任何依赖于for in显示值的人(尤其是对象).更高版本的javascript具有内置于数组中的.map和.filter函数,但这些函数不会出现在for in循环中.如何创建更多不会出现在for in循环中的方法?
Ber*_*rgi 21
这很容易:不要在数组中使用for-in循环.责备所有其他人 - 这是一个很好的片段,在开发过程中告诉他们.
当然,如果在泛型函数中进行枚举并且不知道他是否获得数组,普通对象或具有自定义原型的对象,则可以使用hasOwnProperty如下:
for (var prop in anyObj )
if (Object.prototype.hasOwnProperty.call(anyObj, prop))
// do something
Run Code Online (Sandbox Code Playgroud)
注意显式使用Object.prototype获取函数 - 可能有覆盖它的对象(特别是在数据映射中,值可能不是函数),不支持它的对象或不从Object.prototype继承的对象一点都不 另见这里.
然而,只有知道该问题的脚本作者才会过滤掉他所有的for-in-loops - 有些只是因为它被推荐而做 - 而且大多数错误,他应该使用for循环数组迭代.但我们的问题是那些不知道它的作者.
一个有趣的,但仅Mozilla方法将覆盖数组上的枚举行为__iterate__,如此处所示.
幸运的是,EcmaScript 5.1允许我们将属性设置为不可枚举.当然,旧浏览器不支持此功能,但为什么要这么麻烦?无论如何我们需要使用es5-shims用于所有酷的高阶数组:-)使用defineProperty如下:
Object.defineProperty(Array.prototype, "find", {
enumerable: false,
writable: true,
value: function(testFun) {
// code to find element in array
}
});
Run Code Online (Sandbox Code Playgroud)
根据您的限制:
// In EcmaScript 5 specs and browsers that support it you can use the Object.defineProperty
// to make it not enumerable set the enumerable property to false
Object.defineProperty(Array.prototype, 'find', {
enumerable: false, // this will make it not iterable
get: function(testFun) {
// code to find element in array
};
});
Run Code Online (Sandbox Code Playgroud)
在此处阅读有关Object.defineProperty的更多信息https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty
| 归档时间: |
|
| 查看次数: |
9907 次 |
| 最近记录: |