In Javascript, if there is an object with a lot of properties that are functions, how do you convert them to array of strings (of the function names)?
In Javascript, if an object 开发者_如何学JAVAhas 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.
var names = [];
for( var k in obj ) {
if(obj.hasOwnProperty(k) && typeof obj[k] == 'function') {
names.push(k);
}
}
var functions = [];
for (var prop in obj) {
if ((typeof obj[prop]) == 'function') {
// it's a function
functions.push(prop);
}
}
Edit: I've slightly misread the question, you want to extract the names of only the properties that are function objects:
function methods(obj) {
var result = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] == 'function') {
result.push(prop);
}
}
return result;
}
var obj = {
foo: function() { },
bar: function() { },
};
methods(obj); // ["foo", "bar"]
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 :
var foo = {
constructor : function() { return 0; },
toString : function() { return "1"; },
valueOf : function() { return 2; }
toLocaleString : function() { return "3"; }
};
for (var propName in foo ) { alert(propName); }
The object foo
clearly has defined four own properties, but those properties exist in Object.prototype
marked as DontEnum
, if you try to enumerate the properties of that object with the for-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.
To complete other answers: you can also use instanceof
:
var obj = { foo: function() { ... },
bar: function() { ... },
...
},
fnArr = [];
for (var label in obj){
if (obj[label] instanceof Function){
fnArr.push(label)
}
}
With ES5:
var obj = {
foo: function() {},
bar: function() {},
baz: true
};
function getMethods(object) {
return Object.keys(object).filter(function(key) {
return typeof object[key] == 'function';
});
}
getMethods(obj); // [foo, bar]
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).
精彩评论