drm*_*wer 82 javascript ecmascript-6
我的问题最好通过这个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 );
Run Code Online (Sandbox Code Playgroud)
什么样的数据结构f
?这只是一个简写d
吗?
mad*_*ox2 77
var f = {a, b, c};
Run Code Online (Sandbox Code Playgroud)
它附带ES6(ECMAScript 2015),意思与:
var f = {a: a, b: b, c: c};
Run Code Online (Sandbox Code Playgroud)
它被称为Object Literal Property Value Shorthands(或简称属性值的简写,速记属性).
您还可以将shorthands与经典初始化结合起来:
var f = {a: 1, b, c};
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Object initializer.
voi*_*oid 68
它是ES6中的Object Initializer 属性简写.
var f = {a, b, c, d:1}; // Will be equal to {a:a, b:b, c:c, d:1}
Run Code Online (Sandbox Code Playgroud)
这是因为属性值与属性标识符具有相同的名称.这是最新的ECMAScript 6草案Rev 13中对象初始化器(第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.
}
Run Code Online (Sandbox Code Playgroud)
请参阅兼容性表以获取对这些表示法的支持.在非支持环境中,这些表示法将导致语法错误.
这个简写符号提供了很好的对象匹配:
在ECMAScript5中我们曾经做过:
var tmp = getDate();
var op = tmp.op;
var lhs = tmp.lhs;
var rhs = tmp.rhs;
Run Code Online (Sandbox Code Playgroud)
可以使用一行代码在ECMAScript6中完成:
var { op, lhs, rhs } = getData();
Run Code Online (Sandbox Code Playgroud)
Moj*_*ojo 12
var f = {a, b, c}; // <--- what exactly is this??
Run Code Online (Sandbox Code Playgroud)
它使用新的ECMAScript 2015表示法在JavaScript中定义一个对象:
根据Mozilla开发者网络:
"可以使用新的Object(),Object.create()或使用文字符号(初始化符号)来初始化对象.对象初始值设定项是一对零的或多对属性名称和对象的关联值的列表,包含在大括号 ({})."
var a = "foo",
b = 42,
c = {};
// Shorthand property names (ES6)
var o = { a, b, c };
Run Code Online (Sandbox Code Playgroud)
相当于:
var a = "foo",
b = 42,
c = {};
var o = {
a: a,
b: b,
c: c
};
Run Code Online (Sandbox Code Playgroud)