简体   繁体   English

对象属性分配中的语法错误

[英]Syntax error in object property assignment

Code Academy says there are 2 ways to create objects in JavaScript. Code Academy 说有两种方法可以在 JavaScript 中创建对象。

1. object literal notation 1. 对象字面量表示法

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

2. object constructor approach 2.对象构造方法

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.被要求创建 3 个对象,我尝试了不同的方法来生成具有相同值的对象,但使用上面提供的模板时出现错误。 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. Code Academy 给了我一个错误,为了弄清楚它到底在哪里,我使用了 Chrome 的控制台。 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在 Chrome 的控制台上单独创建每个对象,可以创建object1object2 ,但不能创建object3 ,这会产生错误: Uncaught SyntaxError: Unexpected number

Changing object3 's code to (changing keys from numbers to strings):object3的代码更改为(将键从数字更改为字符串):

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

produces the error: Uncaught SyntaxError: Unexpected string产生错误: 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?是否可以使用此模板/布局创建object3以生成object1值,或者键永远不能是数字或字符串? A string but not a number for the key worked in creating object2 .用于创建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"] ...由于174对点表示法无效,将它们用作键的唯一方法是这样的: obj["4"] ...

Here is an MDN page about the basics of objects.这是一个关于对象基础知识的MDN 页面

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;
@@;

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

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