JavaScript Object is another way to structure data.
Objects can store data in key-value pairs.
Suppose we wanted to model a single person which will include name, age and city data.
This is how we write the data in objects:
var person = {
name: “Marry”,
age: 15,
city: “New York”
};
Every item in this object is a key value pair.It is important to note that objects don’t have any built in order. No property comes first or second. It doesn’t matter how we declared them in what order. They are all treated the same.
Retrieving Data
There are two choices to retrieving data:bracket and dot notation.
console.log(person[“name”]); //bracket
console.log(person.name); // dot notation
Both ways will give the same value which we want to call. The dot notation seems simpler than bracket.
There are three main differences between two notations:
1. You can’t use dot notation if the property starts with a number
For example: someObject.2ac //invalid
2. You can look up using a variable with bracket notation
For example: var string = “name”
someObject.string //this doesn’t look for “name”
someObject[string] //this will evaluate the string and look for “name”
3. You can’t use dot notation for property names with spaces
For example: someObject.fav color //invalid
someObject[“fav color”] //valid
Updating Data
It just like an array: access a property and reassign it. For example, to change the city from New York to Seattle, we need to write:
person[“city”] = “Seattle”;
Objects can hold all sort of data.
Objects can hold all sort of data such as number, string, Boolean, array, and even another objects.
var objects = {
age: 57,
color: “pink”,
isHappy: true,
letters: [“a”, “b”]
}
网友评论