Disclaimer: You are looking at a post I wrote some time ago. The information and opinions contained within may be outdated and may differ from my current views. Please proceed accordingly.

JS Hash Tables and Anonymous Objects

May 13, 2003 4:39 PM
Tags: javascript
I did not know you could do this. Instead of creating an empty object in JS to store keys (properties) and values, you can do it inline:
<script language="javascript" type="text/javascript">
var joe = {name:'joe', age:26}
alert (joe.name + ' ' + joe.age); // says "joe 26"
</script>
From O'Reilly's JavaScript & DHTML Cookbook, by Danny Goodman.
Another syntactical treat — a way to loop through an object's properties without knowing what they are, nor the class of that object:
function listProperties(obj, objName) {
    var result = "";
    for (var i in obj) {
        result += objName + "." + i + "=" + obj[i] + "\n";
    }
    alert(result);
}
However, note:
The type of property enumeration shown in the listProperties( ) function in the Solution is useful not only for custom objects but also for DOM objects. When using it with DOM objects, some browser-specific behaviors reveal themselves. For example, IE for Windows enumerates all of the event handler properties of the object. Netscape 6 and later enumerate properties and methods. Unfortunately, Opera does not handle DOM objects, but the for/in type of looping works with custom objects.

This blog is no longer active, and comments have been disabled.