JavaScript函数参数中的花括号

59

JavaScript函数参数周围的花括号是做什么用的?

var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
4个回答

212

自提出这个问题以来,出现了第二个可能的答案Javascript ES6引入了解构赋值

var x = function({ foo }) {
   console.log(foo)
}

var y = {
  bar: "hello",
  foo: "Good bye"
}

x(y)


Result: "Good bye"

31
非常感谢。这正是我在寻找的答案。更多内容请见此处链接。 - FuzzY
5
这实际上是正确答案,因为问题中指明“对于函数”。 - George Y.

41

花括号表示对象字面量。这是一种发送键/值数据对的方法。

因此,这样做:

var obj = {name: "testing"};

用于访问数据。

obj.name; // gives you "testing"

只要键是唯一的,您可以给对象提供多个逗号分隔的键值对。

var obj = {name: "testing",
           another: "some other value",
           "a-key": "needed quotes because of the hyphen"
          };
你也可以使用方括号来访问对象的属性。 这在"a-key"的情况下是必需的。
obj["a-key"] // gives you "needed quotes because of the hyphen"
使用方括号,可以使用存储在变量中的属性名称来访问一个值。
var some_variable = "name";

obj[ some_variable ] // gives you "testing"

3

Javascript中的花括号被用作创建对象的速记方式。例如:

// Create an object with a key "name" initialized to the value "testing"
var test = { name : "testing" };
alert(test.name); // alerts "testing"

欢迎查看Douglas Crockford的JavaScript Survey,其中包含更多详细信息。


0
var x = {title: 'the title'};

定义一个对象字面量,其中包含其属性。你可以这样做

x.title 

这将被评估为“the title”;

这是一种常见的将配置传递给方法的技术,这就是这里正在发生的事情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接