gpt4 book ai didi

完整的 JavaScript 自省(introspection)

转载 作者:数据小太阳 更新时间:2023-10-29 06:02:25 28 4
gpt4 key购买 nike

初级 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 方法,我不认为这是正确的自省(introspection)。那么,有人可以在这里填写空白吗:

function magic(some_object) {
# magic goes here
}

console.log(magic([])) # should print a list that includes 'length'

或者这根本不可能,或者只适用于“用户类型”?

最佳答案

您需要在浏览器兼容性方面走多远?所有现代浏览器都应该支持 Object.getOwnPropertyNames()。使用您的示例,Object.getOwnPropertyNames([]) 将返回 ["length"]

更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

编辑:其他示例:

  • 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", "一些”、“每个”、“迭代器”、“构造函数”、“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

关于完整的 JavaScript 自省(introspection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17732969/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com