初学JavaScript问题。我有点被Python的dir
内置函数所破坏。我想发现node.js REPL中任何对象的属性/方法。我已经看过this question;在一个空数组node
的简单情况下,接受的答案失败(在[]
REPL中)。例如:
for(var prop in []){console.log(prop);} # returns undefined, prints nothing
[].length # returns 0
由于for
循环没有发现数组的length
方法,所以我不认为这是正确的内省。那么,有人可以填补空白:
function magic(some_object) {
# magic goes here
}
console.log(magic([])) # should print a list that includes 'length'
或者这根本不可能,或者只能用于“用户类型”?
答案 0 :(得分:8)
您需要多长时间才能获得浏览器兼容性?所有现代浏览器都应支持Object.getOwnPropertyNames()
。使用您的示例,Object.getOwnPropertyNames([])
将返回["length"]
。
修改:其他示例:
Object.getOwnPropertyNames([1, 2, 3]);
返回["0", "1", "2", "length"]
Object.getOwnPropertyNames(String);
返回["prototype", "quote", "substring", "toLowerCase", "toUpperCase", "charAt", "charCodeAt", "contains", "indexOf", "lastIndexOf", "startsWith", "endsWith", "trim", "trimLeft", "trimRight", "toLocaleLowerCase", "toLocaleUpperCase", "localeCompare", "match", "search", "replace", "split", "substr", "concat", "slice", "fromCharCode", "length", "name", "arguments", "caller"]
编辑#2:好的,所以看到你正在寻找完整的属性和方法列表,包括继承的属性和方法,我借用了另外两个SO问题(链接如下)并且出现了一个似乎让你更接近的解决方案:
var findProperties = function(obj) {
var aPropertiesAndMethods = [];
do {
aPropertiesAndMethods = aPropertiesAndMethods.concat(Object.getOwnPropertyNames(obj));
} while (obj = Object.getPrototypeOf(obj));
for ( var a = 0; a < aPropertiesAndMethods.length; ++a) {
for ( var b = a + 1; b < aPropertiesAndMethods.length; ++b) {
if (aPropertiesAndMethods[a] === aPropertiesAndMethods[b]) {
aPropertiesAndMethods.splice(a--, 1);
}
}
}
return aPropertiesAndMethods;
}
因此,如果您使用致电findProperties([])
,则会返回["length", "join", "reverse", "sort", "push", "pop", "shift", "unshift", "splice", "concat", "slice", "lastIndexOf", "indexOf", "forEach", "map", "reduce", "reduceRight", "filter", "some", "every", "iterator", "constructor", "toSource", "toString", "toLocaleString", "valueOf", "watch", "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]
关联问题
javascript inheritance, reflection and prototype chain walking?
How to merge two arrays in Javascript and de-duplicate items