在查看 Mozilla (Firefox) 附加 SDK 的一些 Javascript 代码时,我看到了一种以前从未见过的变量声明:
var { foo, bar } = someFunction("whatever"); // just an example
看到变量名周围的花括号了吗?事实证明,这是一种将一个对象的属性值同时分配给多个变量的方法。似乎类似于 destructuring assignment或 PHP 的 list
,除了使用对象属性而不是数组。
我实际上是通过一些摆弄发现的,因为似乎没有关于它的文档。看看这段代码:
function gimmeAnObject() {
return {
foo: "hey",
bar: "sup"
};
}
console.log(gimmeAnObject()); // Object { foo="hey", bar="sup" }
var { foo, bar } = gimmeAnObject();
console.log(foo); // hey
console.log(bar); // sup
我还发现这只适用于 Firefox。 Chrome 将改为抛出错误:“Uncaught SyntaxError: Unexpected token {”。这解释了为什么我在开始查看 Firefox 附加组件代码之前没有看到它。
有没有人见过这种变量声明?为什么我找不到关于它的任何文档?由于它只适用于 Firefox,我认为它可能是 Mozilla 的东西,但我什至在 MDN 上找不到任何关于它的信息。话又说回来,也许我只是不知道要搜索什么。
最佳答案
查看“解构赋值”链接(即 http://en.wikipedia.org/wiki/JavaScript_syntax#Assignment 和 http://dailyjs.com/2011/09/12/destructuring/),看起来这个构造是解构赋值。
维基百科:
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leafs which are to receive the substructures of the assigned value.
在 JavaScript 中,数组和对象或多或少是相同的,因此对象也支持数组支持的构造也就不足为奇了。
关于Javascript - 在变量声明中使用花括号将多个变量分配给对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10526065/