简体   繁体   English

使用Object Literal Notation创建对象的有效Javascript语法是什么?

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

I'm learning Javascript track in codecademy.com. 我正在codecademy.com学习Javascript轨道。 And I'm confused about creating object by using "Object Literal Notation". 我对使用“Object Literal Notation”创建对象感到困惑。

Here syntax1 , in the hint section the syntax is: 这里的syntax1 ,在提示部分中的语法是:

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: 但是,在syntax2中 ,语法是:

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). 其中<valueX>可以是任何JS值,如布尔值,数字,字符串甚至是另一个Object(由相同的{ key1: <value1> ... }语法指示)。

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: synthax1:

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

synthax2: 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. 其他文字是其他价值观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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