在Javascript中相当于Python的目录

Pao*_*olo 44 javascript python namespaces interactive dir

当我从解释器编写Python代码时,我可以键入dir()以获得当前范围中定义的名称列表.当我使用像firebug,chrome console等交互式控制台从浏览器开发Javascript代码时,如何以编程方式获得相同的信息?

And*_*rey 25

Object中有"keys"方法,例如:

Object.keys(object)
Run Code Online (Sandbox Code Playgroud)

但这只返回对象自己的属性和方法.
要列出对象的所有属性和方法,我知道两种可能性:
1.Firefox中的firebug控制台中的console.dir(object)方法和
Google Chrome开发工具中的2.dir(object)方法.


dmi*_*nov 14

如果您需要一个简单的解决方案,这可能对您有用:

function dir(object) {
    stuff = [];
    for (s in object) {
        stuff.push(s);
    }
    stuff.sort();
    return stuff;
}
Run Code Online (Sandbox Code Playgroud)


Gle*_*min 8

在ChatZilla的代码中有一些功能可以做到这一点,你必须正确检查许可证,看看你是否可以将它们撕掉并在任何地方使用它们.

相关功能可在http://hg.mozilla.org/chatzilla/file/59b46c0bf716/js/lib/utils.js#l136 找到 dumpObject,dumpObjectTree


Thi*_*thi 6

您可以使用几个函数来获取所需的数据。

Object.keys()

此函数将返回所有非符号的可枚举拥有的属性。

> let person = {name: 'John Doe', age: 25, [Symbol('Test')] : 'value'}
> Object.keys(person);
['name'] // Note that the Symbol('Test') is not in the returned array!
Run Code Online (Sandbox Code Playgroud)

Object.getOwnPropertyNames()

该函数将返回所有可枚举不可枚举但不是符号的属性。

> Object.getOwnPropertyNames(Set)
[ 'length', 'name', 'prototype' ]
Run Code Online (Sandbox Code Playgroud)

当我们有 时,为什么这个函数很有用Object.keys()

> Object.keys(Set)
[] // Because keys doesn't give you non-enumerable properies
Run Code Online (Sandbox Code Playgroud)

顺便说一句,为什么不给你类似,等等Object.getOwnPropertyNames(Set)的方法?因为他们在. 会产生更好的结果。SetaddhasSet.prototypeObject.getOwnPropertyNames(Set.prototype)

Object.getOwnPropertySymbols()

这将返回您传递给的对象中的所有拥有的属性。Symbol

> let person = {x: 10, Symbol('Test'): 'Test-value' };
> Object.getOwnPropertySymbols(person);
[Symbol(Test)]
Run Code Online (Sandbox Code Playgroud)

Reflect.ownKeys()

这将返回所有拥有的属性,这些属性是您传递给的对象中的字符串/符号。

> let person = {x: 1, [Symbol('Test')]: 'Test-value'};
> Reflect.ownKeys(person);
[ 'x', Symbol(Test) ]
Run Code Online (Sandbox Code Playgroud)

奖金:

Object.getPrototypeOf()

这将返回Prototype传递给它的对象的 。

> let nameable = { name: 'name' };
> let ageable = Object.create(nameable);
> ageable.age = 0;
> let person = Object.create(ageable);
> let proto_of_person = Object.getPrototypeOf(person);
> proto_of_person === ageable;
true
> let proto_of_ageable = Object.getPrototypeOf(proto_of_person);
> proto_of_ageable === nameable
true
Run Code Online (Sandbox Code Playgroud)

使用它,我们可以递归地枚举对象及其原型链的所有属性。


Pro*_*one 5

Google Chrome 开发者工具控制台有一个预定义的目录:https : //developers.google.com/chrome-developer-tools/docs/console

Firebug 有 console.dir:http : //getfirebug.com/logging