Javascript对象文字:究竟是什么{a,b,c}?

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)

  • 为什么这对于成为语言特征会如此有用?人们似乎更常见的是直接用文字初始化对象,返回值等,或者只是首先创建对象,然后直接设置属性.创建具有相同名称的变量,实例化它们,然后最终像这样初始化对象似乎不寻常......或者是这样吗? (9认同)
  • @Panzercrisis看起来它会导致很多无意识的并且很难找到个人的错误.与允许`if(a = 1){...}`作为有效语法的方式大致相同. (3认同)
  • @Alex 这是“怪癖”还是“复杂”?您通常在许多代码库中发现的一个非常常见的事情是初始化一个对象,其中键与作为值给定的变量相匹配。到当地的然后回来。在大多数情况下,您不想稍微不同地命名您的东西`{identifier: id, viewData: data, isElementSelected: isSelected }` 正是您所谈论的“古怪”、“复杂”和“令人困惑”。 (2认同)

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)