[英]Javascript object literal: what exactly is {a, b, c}?
我的问题最好通过这个 jsfiddle 给出,其代码如下:
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
的简写吗?
var f = {a, b, c};
它随 ES6 (ECMAScript 2015) 一起提供,含义与以下内容完全相同:
var f = {a: a, b: b, c: c};
它被称为 Object Literal Property Value Shorthands(或简称为属性值速记,速记属性)。
您还可以将速记与经典初始化结合起来:
var f = {a: 1, b, c};
有关详细信息,请参阅对象初始化程序。
它是 ES6 中的对象初始化器属性简写。
var f = {a, b, c, d:1}; // Will be equal to {a:a, b:b, c:c, d:1}
这是有效的,因为属性值与属性标识符具有相同的名称。 这是最新的ECMAScript 6 草案 Rev 13中对Object Initialiser (第 11.1.5 节)语法的新增内容。 当然,就像 ECMAScript 3 中设置的限制一样,您不能使用保留字作为属性名称。
这样的速记不会显着改变你的代码,它只会让一切变得更甜蜜!
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.
}
请参阅兼容性表以获取对这些符号的支持。 在不支持的环境中,这些符号会导致语法错误。
这个速记符号很好地提供了对象匹配:
在ECMAScript5中我们曾经做过的事情:
var tmp = getData();
var op = tmp.op;
var lhs = tmp.lhs;
var rhs = tmp.rhs;
可以在ECMAScript6中用一行代码完成:
var { op, lhs, rhs } = getData();
var f = {a, b, c}; // <--- what exactly is this??
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.