[英]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.