Jump to content

javaSCript objects - change


crazyswede

Recommended Posts

It's simpler than that. The chapter about objects is here: http://www.w3schools.com/js/js_objects.asp

 

To create an object, the syntax is as you showed.

var ObjectName = {
  aaaa: "red",
  bbb: "blue"
};

To modify the properties of the object, just use the dot operator and then treat the properties as you would any variable;

ObjectName.aaaa = "orange";
ObjectName.bbb = "green";
Link to comment
Share on other sites

You can also access properties using square brackets like an array index:

ObjectName["aaaa"] = "orange";
ObjectName["bbb"] = "green";

There probably aren't many cases where this would be useful or preferred over dot syntax, but there are a few...

 

 

EDIT:

One simple example would be if you needed to loop through all the properties of an object:

for (propertyName in ObjectName) {
    ObjectName[propertyName] = "yellow";
}
Edited by ShadowMage
Link to comment
Share on other sites

I've actually used it a couple times. One such example: I have a table of values that changes depending on parameters set elsewhere in the page. I use AJAX to send the parameters to PHP and calculate the values then send those values back as a JSON object. I loop through the rows of values like a normal numeric array. I then loop through the "properites" (ie, columns) of each row and update the values in the table.

Link to comment
Share on other sites

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