[英]Equivalent of Python's dir in Javascript
當我從解釋器編寫 Python 代碼時,我可以輸入dir()
以獲得在當前作用域中定義的名稱列表。 當我使用交互式控制台(如 firebug、chrome 控制台等)從瀏覽器開發 Javascript 代碼時,如何以編程方式獲得相同的信息?
Object
有keys
方法,例如:
Object.keys(object)
但是這個只返回對象自己的屬性和方法。
要列出對象的所有屬性和方法,我知道有 2 種可能性:
console.dir(object)
方法和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 建議的函數)
另一方面,我不知道有什么方法可以檢查函數或閉包中定義的局部變量——如果可能的話,我至少猜測它是高度特定於瀏覽器/控制台的。
那么你可以看到對象只包含它自己的屬性:通過它可以在任何控制台中工作,不僅谷歌瀏覽器網絡瀏覽器查找 img在此處輸入圖像描述console.dir(obj); 這里鏈接: https : //developers.google.com/web/tools/chrome-devtools/console/console-reference
您可以使用幾個函數來獲取所需的數據。
Object.keys()
此函數將返回所有可枚舉的、非Symbols擁有的屬性。
> 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()
此函數將返回所有不是Symbols的可枚舉和不可枚舉的屬性。
> Object.getOwnPropertyNames(Set)
[ 'length', 'name', 'prototype' ]
為什么當我們有Object.keys()
時這個函數很有用?
> Object.keys(Set)
[] // Because keys doesn't give you non-enumerable properies
Object.getOwnPropertyNames(Set)
,為什么Object.getOwnPropertyNames(Set)
不給你像add
、 has
等Set
的方法? 因為它們在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
。
> 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
使用它,我們可以遞歸地枚舉對象及其原型鏈的所有屬性。
(只是為了看到那個列表)
您可以使用運算符“.”,例如:
> var a = "asdfg";
> a. // -> show the list
首先,創建一個列出對象所有屬性的函數:
function dir(object) {
props = [];
for (prop in object) {
props.push(prop);
}
props.sort();
return props;
}
然后,盡可能簡單地調用console.log(dir(console))
類的函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.