简体   繁体   English

javascript中的对象文字如何工作?

[英]How do object literals in javascript work?

Im having some trouble understanding the syntax of object literals in javascript when considering the following code sample (from Mozilla's developer site): 在考虑以下代码示例(来自Mozilla的开发人员网站)时,我在理解javascript中对象文字的语法时遇到了一些麻烦:

var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda

My current understanding of javascript object literals is this: If you give a key, value pair and the key is of a data type, it works something like a python dictionary, making car[key] return the value you set to the key. 我目前对javascript对象文字的理解是:如果给定键,值对,并且键为数据类型,则它的工作方式类似于python字典,使car [key]返回您设置为键的值。 If you give a key as just text, it defines a variable in 'car' set to the value you associated with the key. 如果您仅将密钥作为文本提供,它将在“ car”中定义一个变量,该变量设置为您与该密钥关联的值。 However, in the above, "b" is a string, but car.manyCars.b can be called as if it were a variable set to "Jeep" , AND ALSO car.manyCars["b"] is valid syntax, returning "Jeep" . 但是,在上面的代码中, "b"是一个字符串,但是可以将car.manyCars.b当作一个变量设置为"Jeep" ,并且car.manyCars["b"]是有效的语法,返回"Jeep"

I was wondering if somebody could give me a clear explanation of what actually happens when you declare an object literal, because clearly my current understanding is not complete. 我想知道是否有人可以对我在声明对象文字时实际发生的情况给出清晰的解释,因为显然我目前的理解还不完整。

In JavaScript, the keys in object literal notation are treated as strings whether or not they are in quotes. 在JavaScript中,对象文字表示法中的键无论是否用引号括起来都被视为字符串。 Thus, with this: 因此,与此:

var car = { manyCars : {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

If you then do this: 如果您这样做,请执行以下操作:

for (var k in car) { console.log("key: " + k + " (type: " + typeof(k) + ")"); }

the output will be: 输出将是:

key: 7 (type: string) 键:7(类型:字符串)
key: manyCars (type: string) 键:manyCars(类型:字符串)

Note that the (apparently) numeric key 7 is also a string . 注意(显然)数字键7也是一个string You can even use JavaScript keywords as keys in an object literal. 您甚至可以将JavaScript关键字用作对象文字中的键。

Note that when accessing a value by key, the rules are more stringent. 请注意,通过键访问值时,规则更加严格。 For instance, you must use subscript notation and quotes when a key is a reserved word. 例如,当键是保留字时,必须使用下标符号和引号。 Also, a bare key in an object literal must (if it isn't a numeric literal) be a valid JavaScript identifier name, so it cannot contain spaces, commas, or JavaScript operators ( + , = , etc.). 同样,对象文字中的裸键必须(如果不是数字文字)必须是有效的JavaScript标识符名称,因此它不能包含空格,逗号或JavaScript运算符( +=等)。

In JavaScript objects literals are made up of key-value pairs. 在JavaScript对象中,文字由键值对组成。 Keys in JavaScript are always strings while values may be of any data type. JavaScript中的键始终是字符串,而值可以是任何数据类型。

JavaScript provides syntactic sugar for defining keys. JavaScript提供了用于定义键的语法糖。 For example unlike string literals you don't need to quote keys. 例如,与字符串文字不同,您不需要引用键。 Hence the following two examples are equivalent: 因此,以下两个示例是等效的:

{ x: 0 }   // example 1
{ "x": 0 } // example 2

However this syntactic sugar only works for identifiers that don't have any whitespace (ie spaces, tabs, newlines, etc.) in between them. 但是,此语法糖仅适用于它们之间没有任何空格(即空格,制表符,换行符等)的标识符。 For example, the following is invalid in JavaScript: 例如,以下在JavaScript中无效:

{ a property: 0 } // whitespace not allowed in identifiers

However you can workaround this limitations by quoting the identifier: 但是,您可以通过引用标识符来解决此限制:

{ "a property": 0 } // valid

You may also use boolean ( true or false ), number literals and undefined and null as keys. 您还可以使用布尔值( truefalse ),数字文字以及undefinednull作为键。 However remember that they are coerced to strings. 但是请记住,它们被强制为字符串。 Hence you can do: 因此,您可以执行以下操作:

var o = {
    undefined: 1,
    null: 2,
    true: 3,
    false: 4,
    0: 5
};

Then you can access them as: 然后,您可以通过以下方式访问它们:

alert(o.undefined); // 1
alert(o.null);      // 2
alert(o.true);      // 3
alert(o.false);     // 4
alert(o[0]);        // 5

The last statement is important. 最后的声明很重要。 Number literals by themselves do not classify as valid identifiers. 数字文字本身不能归类为有效标识符。 Hence you need to use the array bracket notation ( [] ) instead of the dot notation ( . ) to access it. 因此,您需要使用数组括号符号( [] )而不是点符号( . )来访问它。

Since all keys in JavaScript are strings you could even do: 由于JavaScript中的所有键都是字符串,因此您甚至可以:

alert(o["undefined"]); // 1
alert(o["null"]);      // 2
alert(o["true"]);      // 3
alert(o["false"]);     // 4
alert(o["0"]);         // 5

However you can't use objects, arrays or functions as keys. 但是,不能将对象,数组或函数用作键。 For example the following is invalid: 例如,以下内容无效:

{ {1: 2}: 3 }            // objects can't be used as keys
{ [1]: 2 }               // arrays can't be used as keys
{ function () {}: true } // functions can't be used as keys

That's all you need to know about object literals. 这就是有关对象文字的所有信息。

Essentially an object literal in javascript operates very similar to a dictionary but also has the functionality of an object in Java or PHP. 本质上,JavaScript中的对象文字与字典非常相似,但具有Java或PHP中的对象功能。 The objects can have functions defined within or properties, or both. 这些对象可以具有在函数中定义的功能,在属性中定义的功能,或在两者中定义的功能。 You can use quotes or dot syntax depending on the keys you are trying to access. 您可以根据引用的键使用引号或点语法。 Some may have special characters, then you'd want to use the quotes, if no special characters, use dot. 有些可能带有特殊字符,那么您需要使用引号,如果没有特殊字符,请使用点号。 Both are correct. 两者都是正确的。

Here is a useful resource comparing and contrasting the difference between creating object literals and creating objects by constructor. 这是一个有用的资源,用于比较和对比创建对象文字和通过构造函数创建对象之间的区别。

http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/ http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/

Here's another one going more in depth on the use of object literals 这是关于对象字面量使用的另一个更深入的探讨

http://javascript.info/tutorial/objects http://javascript.info/tutorial/objects

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

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