javascript 变量名周围的{花括号}是什么意思 [英] What do {curly braces} around javascript variable name mean

查看:104
本文介绍了javascript 变量名周围的{花括号}是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑在查看 JSHint 后,我​​发现这个解构表达式"在 ES6(使用 esnext 选项)或 Mozilla JS 扩展(使用 moz)this 但是在阅读之后我仍然不明白为什么使用它

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

我在 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?

推荐答案

这就是所谓的 解构赋值,这是JavaScript 1.7(和 ECMAScript 6)(目前,仅作为 Firefox JavaScript 引擎的一部分可用.)粗略地说,它会转化为:

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 as part of the Firefox JavaScript engine.) Roughly, it would translate into this:

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;

相当于:

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];

<小时>

可以使用 kangax 的 ES6 兼容性表跟踪浏览器支持情况.

这篇关于javascript 变量名周围的{花括号}是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆