当我从解释器编写 Python 代码时,我可以键入dir()
在当前范围内定义的名称列表。当我使用 firebug、chrome 控制台等交互式控制台从浏览器开发 Javascript 代码时,如何以编程方式获得相同的信息?
9 回答
中有keys
方法Object
,例如:
Object.keys(object)
但这仅返回对象自己的属性和方法。
要列出对象的所有属性和方法,我知道 2 种可能性:
console.dir(object)
Firefox 的 firebug 控制台中的方法和dir(object)
谷歌浏览器开发工具中的方法。
如果您需要一个简单的解决方案,这可能对您有用:
function dir(object) {
stuff = [];
for (s in object) {
stuff.push(s);
}
stuff.sort();
return stuff;
}
ChatZilla 的代码中有几个功能可以做到这一点,你必须正确检查许可证,看看你是否可以把它们撕下来并在任何地方使用它们。
相关函数可以在
http://hg.mozilla.org/chatzilla/file/59b46c0bf716/js/lib/utils.js#l136
dumpObject
和dumpObjectTree
Google Chrome 开发者工具控制台有一个预定义的目录:https ://developers.google.com/chrome-developer-tools/docs/console
Firebug 有 console.dir: http: //getfirebug.com/logging
全局变量保存在一个易于访问的对象 ( window
) 中,因此您可以轻松地检查/迭代它们。(使用类似于 Glenjamin 建议的功能)
另一方面,我不知道有什么方法可以检查函数或闭包中定义的局部变量——如果可能的话,我至少猜想它是高度特定于浏览器/控制台的。
您可以使用几个函数来获取所需的数据。
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!
Object.getOwnPropertyNames()
此函数将返回所有不是符号的可枚举和不可枚举的属性。
> Object.getOwnPropertyNames(Set)
[ 'length', 'name', 'prototype' ]
为什么我们有这个函数有用Object.keys()
?
> Object.keys(Set)
[] // Because keys doesn't give you non-enumerable properies
顺便说一句,为什么不Object.getOwnPropertyNames(Set)
给你方法Set
like add
, has
, etc., ?因为他们在Set.prototype
。Object.getOwnPropertyNames(Set.prototype)
会产生更好的结果。
Object.getOwnPropertySymbols()
这将返回您传递给的 Object 中的所有拥有的属性。Symbol
> let person = {x: 10, Symbol('Test'): 'Test-value' };
> Object.getOwnPropertySymbols(person);
[Symbol(Test)]
Reflect.ownKeys()
这将返回所有拥有的属性,这些属性是您传递给的对象中的字符串/符号。
> let person = {x: 1, [Symbol('Test')]: 'Test-value'};
> Reflect.ownKeys(person);
[ 'x', Symbol(Test) ]
奖金:
Object.getPrototypeOf()
这将返回Prototype
传递给它的 Object 。
> 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
使用它,我们可以递归地枚举对象及其原型链的所有属性。
好吧,您可以看到对象仅包含其自己的属性:它可以在任何控制台中工作,不仅是 google chrome 网络浏览器查找 img在此处输入图像描述 console.dir(obj); 此处链接:https ://developers.google.com/web/tools/chrome-devtools/console/console-reference
(只是为了看到那个列表)
您可以使用运算符“.”,例如:
> var a = "asdfg";
> a. // -> show the list
- 在 chrome 控制台中,它会显示自动完成的选项列表
- 在 node.js 控制台中,您可以执行相同操作并按两次 tab 以查看列表
真正的解决方案
首先,创建一个列出对象所有属性的函数:
function dir(object) {
props = [];
for (prop in object) {
props.push(prop);
}
props.sort();
return props;
}
然后,尽可能简单地调用函数console.log(dir(console))