This question already has an answer here:
这个问题在这里已有答案:
- What is this JavaScript syntax: {Ci, CC}? [duplicate] 2 answers
- 这是什么JavaScript语法:{Ci,CC}? [重复] 2个答案
EDIT After looking at JSHint I found this 'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz) and this however after reading it I still don't understand why it is used
编辑在查看JSHint之后我发现这个“解构表达式”在ES6(使用esnext选项)或Mozilla JS扩展(使用moz)中可用,然而这在阅读之后我仍然不明白为什么使用它
I have come across the following code on MDN
我在MDN上遇到了以下代码
var ui = require("sdk/ui");
var { ActionButton } = require("sdk/ui/button/action");
What do the braces on the second line do and why are they used? Why are there no braces on the first line?
第二行的括号是什么以及为什么使用它们?为什么第一行没有括号?
1 个解决方案
#1
133
This is what's known as a destructuring assignment, and it's a new feature of JavaScript 1.7 (and ECMAScript 6) (Currently, only available in the FireFox JavaScript engine.) Roughly, it would translate into this:
这就是所谓的解构赋值,它是JavaScript 1.7(和ECMAScript 6)的一个新特性(目前,仅在FireFox JavaScript引擎中可用。)粗略地说,它将转化为:
var ActionButton = require("sdk/ui/button/action").ActionButton;
It seems silly in this example, as there's only one item being assigned. However, you'd be able to use this pattern to assign multiple variables at once:
在这个例子中似乎很愚蠢,因为只分配了一个项目。但是,您可以使用此模式一次分配多个变量:
{x, y} = foo;
Is the equivalent to:
相当于:
x = foo.x;
y = foo.y;
This can also be used for arrays. For example, you could easily swap two values without using a temporary variable:
这也可以用于数组。例如,您可以轻松地交换两个值而不使用临时变量:
var a = 1;
var b = 3;
[a, b] = [b, a];
Browser support can be tracked using kangax' ES6 compatibility table.
可以使用kangax的ES6兼容性表跟踪浏览器支持。
#1
133
This is what's known as a destructuring assignment, and it's a new feature of JavaScript 1.7 (and ECMAScript 6) (Currently, only available in the FireFox JavaScript engine.) Roughly, it would translate into this:
这就是所谓的解构赋值,它是JavaScript 1.7(和ECMAScript 6)的一个新特性(目前,仅在FireFox JavaScript引擎中可用。)粗略地说,它将转化为:
var ActionButton = require("sdk/ui/button/action").ActionButton;
It seems silly in this example, as there's only one item being assigned. However, you'd be able to use this pattern to assign multiple variables at once:
在这个例子中似乎很愚蠢,因为只分配了一个项目。但是,您可以使用此模式一次分配多个变量:
{x, y} = foo;
Is the equivalent to:
相当于:
x = foo.x;
y = foo.y;
This can also be used for arrays. For example, you could easily swap two values without using a temporary variable:
这也可以用于数组。例如,您可以轻松地交换两个值而不使用临时变量:
var a = 1;
var b = 3;
[a, b] = [b, a];
Browser support can be tracked using kangax' ES6 compatibility table.
可以使用kangax的ES6兼容性表跟踪浏览器支持。