Can I drill down into all of the properties of an object in javascript at runtime?
I have an object being passed to a method from a flash object. I would like to be able to view all of the properties in this object a bit like you can do in c# with the 'add watch' feature in visual studio.
Is this possible with javascript and firef开发者_Python百科ox/firebug?
I was thinking of doing a for loop and console.logging the results but what is the best way to iterate the object would I treat it as an array etc?
Any advice much appreciated. Pete
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
console.log(p + ': ' + obj.p);
}
}
Objects in JavaScript inherit through their prototype, and their prototype can also have a prototype. Using the hasOwnProperty
method (inherited from Object) checks to see if the property exists on the object you're examining and not associated with its prototype.
Techically, in JS an object is +- an associative array string->value
, so....
for (var key in someObject) {
// key is a string
var value = someObject[key];
// ...
}
Usually you can just use the for (prop in obj) { }
syntax.
for (var prop in obj) {
console.log(obj[name]);
}
in jQuery there is the jQuery.each() method, which allows a callback on each entry:
jQuery.each(obj, function(index, prop) {
console.log(prop);
});
精彩评论