如何枚举数组的原型
How Enumerate the Prototypes of Array
如果我创建这样的数组。。。
var arr = [1,2,3];
变量"arr"将具有各种原型,如"toString"answers"forEach"。我如何枚举"arr"的所有原型的名称,并得到一个列表,如"concat"、"constructor"、"entries"、"every"等等?
这里有一种递归方法来打印prototype chain
中的所有属性,而不仅仅是在第一个原型中,就像在其他答案中一样:
var arr = [1, 2, 3];
printAllPrototypeProperties(arr);
function printAllPrototypeProperties(obj) {
var proto = Object.getPrototypeOf(obj);
if (proto != null) {
var properties = Object.getOwnPropertyNames(proto);
document.body.appendChild(document.createElement('pre')).innerHTML = (JSON.stringify(properties, undefined, 3));
return printAllPrototypeProperties(proto);
}
}
在firefox:中工作
Object.getOwnPropertyNames(Object.getPrototypeOf([]));
Object.getOwnPropertyNames(Array.prototype); //same thing.
/*
result:
length,toSource,toString,toLocaleString,join,reverse,sort,push,pop,shift,unshift,splice,concat,slice,lastIndexOf,indexOf,forEach,map,reduce,reduceRight,filter,some,every,find,findIndex,copyWithin,fill,@@iterator,entries,keys,constructor
*/
最好的方法是使用以下4行代码。
var forEach = Array.prototype.forEach;
forEach.call(Object.getOwnPropertyNames([].__proto__), function(val) {
console.log(val);
});
你也可以直接使用forEach,但我的终端只有80个字符长。
相关文章:
- 为什么不't loadash/aunderline将util方法放在数组原型上
- 用于数组原型的JavaScript独特方法
- 在JavaScript中更改数组原型
- 如何在数组原型图中获取当前索引
- 将数组原型函数与非数组一起使用
- Javascript:分配给对象或数组原型会导致括号不起作用
- Javascript 自定义数组原型
- 为什么在 javascript 中向数组原型添加方法会破坏 for 循环上的迭代
- 使用数组原型Slice调用
- 如何通知TypeScript编译器JS数组原型的扩展
- 在数组原型中循环
- 如何在我自己的数组原型函数中使用数组函数
- JavaScript数组.原型如何设置'this'到由方法获得的新数组
- 修改数组原型会导致foreach的行为不同
- JS函数给数组.原型被视为数组属性
- JavaScript数组原型,'this'没有'push'方法
- 由于将比较方法添加到数组原型而导致测试失败.如何更新代码或测试?
- 字符串vs数组原型Javascript
- 如何创建一个Javascript哈希表/关联数组原型
- 扩展数组.原型在Node.js中,从一个require'd文件