在Javascript中,如果有一个对象具有很多函数属性,如何将它们转换为字符串数组(函数名称)?
在 Javascript 中,如果一个对象有很多函数属性:
var obj = { foo: function() { ... },
bar: function() { ... },
...
}
那么如何获得这些函数的名称数组呢?也就是说,一个数组,
["foo", "bar", ... ]
谢谢。
In Javascript, if an object has lots of properties that are functions:
var obj = { foo: function() { ... },
bar: function() { ... },
...
}
then how can you get an array of names of those functions? That is, an array
["foo", "bar", ... ]
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
编辑:我稍微误读了这个问题,您只想提取仅作为函数对象的属性的名称:
我正在使用
hasOwnProperty
方法,保证枚举的属性事实上物理上存在于物体中。请注意,这种方法和所有其他答案都有一个小问题 IE。
JScript 的 DontEnum Bug,隐藏不可枚举属性的自定义属性 (
DontEnum
)原型链中较高的部分,不使用 for-in 语句进行枚举,例如:对象
foo
明确定义了四个自己的属性,但这些属性存在于Object 中.prototype
标记为DontEnum
,如果您尝试在 IE 中使用for-in
语句枚举该对象的属性,它将找不到任何属性。此错误存在于所有 IE 版本中,最近已在 IE9 平台预览版中修复。
Edit: I've slightly misread the question, you want to extract the names of only the properties that are function objects:
I'm using the
hasOwnProperty
method, to ensure that the enumerated properties in fact exist physically in the object.Note that this approach and all other answers have a small problem IE.
The JScript's DontEnum Bug, custom properties that shadow non-enumerable properties (
DontEnum
) higher in the prototype chain, are not enumerated using the for-in statement, for example :The object
foo
clearly has defined four own properties, but those properties exist inObject.prototype
marked asDontEnum
, if you try to enumerate the properties of that object with thefor-in
statement in IE, it won't find any.This bug is present on all IE versions, and has been recently fixed in IE9 Platform Preview.
要完成其他答案:您还可以使用
instanceof
:To complete other answers: you can also use
instanceof
:使用 ES5:
Object.keys(
示例 - 适用于 Chrome 版本和 Webkit 和 Tracemonkey (Firefox)。
With ES5:
Object.keys(<object>)
returns the names of all enumerable properties of an object as an array, of which the non-functions are filtered out.Example - works on Chrome release and nightly builds of Webkit and Tracemonkey (Firefox).