简体   繁体   中英

Syntax error in object property assignment

Code Academy says there are 2 ways to create objects in JavaScript.

1. object literal notation

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

2. object constructor approach

var myObject = new Object();

Keys can then be added thus:

myObj["name"] = "Charlie"; 
myObj.name = "Charlie"; //shorthand for the first

Being asked to create 3 objects, I tried different ways to produce the objects with the same values but I am getting an error using the template provided above. My code is pasted below:

var object1 = {
    1: 2,
    7: 3,
    4: 5
};

var object2 = new Object();
object2['1'] = 2;
object2['7'] = 3;
object2['4'] = 5;

var object3 = new Object();
object3.1 = 2;
object3.7 = 3;
object3.4 = 5;

Code Academy gave me an error and to figure out where exactly it was, I used Chrome's console. Tying each object creation separately on Chrome's console, object1 and object2 could be created but not object3 which produces the error: Uncaught SyntaxError: Unexpected number

Changing object3 's code to (changing keys from numbers to strings):

var object3 = new Object();
object3.'1' = 2;
object3.'7' = 3;
object3.'4' = 5;

produces the error: Uncaught SyntaxError: Unexpected string

Is it possible to create object3 using this template/layout to produce values of object1 or can the key never be a number or string? A string but not a number for the key worked in creating object2 .

When using the dot notation , the keys should be named in the same way variables are ( starts with a letter or _ and contains only letters, numbers and _ ).

If the key is not valid to be used as dot notation then it can be used using bracket notation like this:

obj["key goes here"];

Since 1 , 7 and 4 are not valid for dot notation, the only way to use them as key is like this: obj["4"] ...

Here is an MDN page about the basics of objects.

Example:

These keys are valid for dot notation:

abc;
_a;
R2D2;
_;
_0;
a________a;

Thes are not:

k-ey;
a b a;
99;
k.e.y;
@@;

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