Javascript 对象字面量:{a, b, c} 到底是什么? [英] Javascript object literal: what exactly is {a, b, c}?
问题描述
我的问题最好通过this jsfiddle给出,其代码如下:
The question I have is best given by way of this jsfiddle, the code for which is below:
var a = 1, b = 'x', c = true;
var d = {a: a, b: b, c: c}; // <--- object literal
var e = [a, b, c]; // <--- array
var f = {a, b, c}; // <--- what exactly is this??
// these all give the same output:
alert(d.a + ', ' + d.b + ', ' + d.c );
alert(e[0] + ', ' + e[1] + ', ' + e[2]);
alert(f.a + ', ' + f.b + ', ' + f.c );
f
是一种什么样的数据结构?它只是 d
的简写吗?
What sort of a data structure is f
? Is it just a shorthand for d
?
推荐答案
It is an Object Initializer ES6 中的属性简写.
It is an Object Initializer Property Shorthand in ES6.
var f = {a, b, c, d:1}; // Will be equal to {a:a, b:b, c:c, d:1}
这是有效的,因为属性值与属性标识符具有相同的名称.这是对象初始化器(第 11.1.5 节)在最新的 ECMAScript 6 草案 Rev 13.当然,就像 ECMAScript 3 设置的限制一样,您不能使用保留字作为属性名称.
This works because the property value has the same name as the property identifier. This a new addition to the syntax of Object Initialiser (section 11.1.5) in the latest ECMAScript 6 draft Rev 13. And of course, just like the limitations set from ECMAScript 3, you can’t use a reserved word as your property name.
这样的速记不会显着改变您的代码,只会让一切变得更甜蜜!
Such a shorthand won’t dramatically change your code, it only makes everything a little bit sweeter!
function createCar(name, brand, speed) {
return { type: 'Car', name: name, brand: brand, speed: speed };
}
// With the new shorthand form
function createSweetCar(name, brand, speed) {
return { type: 'Car', name, brand, speed }; // Yes it looks sweet.
}
请参阅兼容性表以获取对这些符号的支持.在不支持的环境中,这些符号会导致语法错误.
Please see the compatibility table for support for these notations. In non-supporting environments, these notations will lead to syntax errors.
这个速记符号提供了非常好的对象匹配:
在 ECMAScript5 中,我们曾经做过:
In ECMAScript5 what we used to do:
var tmp = getData();
var op = tmp.op;
var lhs = tmp.lhs;
var rhs = tmp.rhs;
可以在 ECMAScript6 中用一行代码完成:
Can be done in ECMAScript6 with a single line of code:
var { op, lhs, rhs } = getData();
这篇关于Javascript 对象字面量:{a, b, c} 到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!