简体   繁体   中英

What is the valid Javascript syntax for creating an object by using Object Literal Notation?

I'm learning Javascript track in codecademy.com. And I'm confused about creating object by using "Object Literal Notation".

Here syntax1 , in the hint section the syntax is:

var friends = {
    bill: {},
    steve: {}
};

We need those curly braces to contain keys' values within the object's curly brace.

BUT, in syntax2 , the syntax is:

var myObject = {
    key: value,
    key: value,
    key: value
};

See, no need for curly braces container within the object's curly brace. As I did the exercise we only required to: direct input for numbers and functions, or within quotation for strings, or within square brackets for arrays.

Can someone kindly share their knowledge and time to tell me why we have the difference or which one is the correct syntax?

The "Object Literal Notation" just means the following format:

var myObject = {
    key1: <value1>,
    key2: <value2>,
    // ...
    keyN: <valueN>
};

where <valueX> can be any JS value, like a boolean, a number, a string or even another Object (which is indicated by the same { key1: <value1> ... } syntax).

An empty object is just one that has no keys (properties) and thus looks like { } (space is optional).

It depends on what will be the content of your variables:

synthax1:

var obj = {
    name: "Thiago",
    currentYear : 2014
};

synthax2:

    var obj = {
        name: "Thiago",
        skills: {
           key: "JS",
           value: 1
        }

};

you can initialize with [] and it will be an array.

It depends what you want the values to be.

{} is an empty object; other literals are other values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM