Search the Community
Showing results for tags 'Object accessors'.
-
// four variables are created and assigned in a single go, // separated by commas var myObj = new Object(), str = "myString", rand = Math.random(), obj = new Object(); myObj.type = "Dot syntax"; myObj["date created"] = "String with space"; myObj[str] = "String value"; myObj[rand] = "Random Number"; myObj[obj] = "Object"; myObj[""] = "Even an empty string"; console.log(myObj); function showProps(obj, objName) { var result = ""; for (var i in obj) { if (obj.hasOwnProperty(i)) { result += objName + "." + i + " = " + obj[i] + "\n"; } } return result; } Ok. That's a code example from mdn: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects now I am wondering if using the showProps function, how to access 1. the "date created" property (or any prop with spaces) 2. the "rand" property (or any prop with number) myObj["date created"] shows correctly. myObj["object Object"] how to access ? myObj[rand] works because the key name is stored in that var... when using the the function passing "date created" won't work. Or any other spaced string. It shows undefined or throws error of mmissing "]" even its present.... So i wonder how to acces all the properties correctly. Is it even possible tow access them somehow by index as in an array? Because the property name for "rand" of course results in a random number...