[Javascript] Getting object property names as a string

Scott Reynen scott at randomchaos.com
Wed May 24 13:14:49 CDT 2006


On May 24, 2006, at 12:21 PM, Ryan Cannon wrote:

> Greetings, this feels like a silly question, but I'm looking for a  
> way to access an object's property names as a string. For example:
>
> var test = { foo: 'bar' };
> alert(test.foo) // alerts 'bar'
>
> how do I alert('foo') ?

There may be a simpler way, but this is how I'd do it:

for ( var i in test ) { alert( i ); }

Beware: the above will likely cause you to force-quit your browser if  
test is a DOM node.  After making that mistake three or four times, I  
learned to write to the DOM instead of alerts when I'm debugging  
objects.

Peace,
Scott



More information about the Javascript mailing list