Jump to content

Question about accessing objects...


antidot

Recommended Posts

// 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...

 

 

Link to comment
Share on other sites


<script>

var myObj = {

str: "myString",

rand: Math.random(),

obj: {},

type: "Dot syntax",

date_created: "String with space"

}

myObj.str = "String value";

alert(myObj.str);

myObj.rand = "Random Number";

alert(myObj.rand);

myObj.obj = {objstring: "Even an empty string"};

alert(myObj.obj.objstring);

</script>

Link to comment
Share on other sites

You access the property exactly the way it shows:

 

myObj["date created"]
If you have a number or other value in a variable, then you can use the variable also:

 

myObj[var]

Is it even possible tow access them somehow by index as in an array?

Yes, that is exactly what those examples show. You can use dot syntax if the property name is a valid identifier, or else you use array syntax.
Link to comment
Share on other sites

  • 1 month later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...