Learn Coding From Zero

JavaScript Basics: Study Note For Objects

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:

  • You can’t use dot notation if the property starts with a number

For example: someObject.2ac //invalid

  • 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”

  • 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”]
}

留下评论