如何枚举数组的原型

How Enumerate the Prototypes of Array

本文关键字:数组 原型 枚举 何枚举      更新时间:2023-09-26

如果我创建这样的数组。。。

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个字符长。