用于方法的Javascript参数内的大括号

mil*_*lan 30 javascript parameters function curly-braces

围绕方法的javascript参数的花括号有什么作用?

var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
Run Code Online (Sandbox Code Playgroud)

Mat*_*tW. 105

一个第二个可能的答案已经出现,因为这问题有人问.Javascript ES6引入了Destructuring Assignment.

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

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

x(y)


Result: "Good bye"
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢.这正是我一直在寻找的答案.[更多此处.](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) (21认同)
  • 这实际上是正确的答案,因为问题指出“对于功能”。 (3认同)

use*_*716 33

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

所以这:

var obj = {name: "testing"};
Run Code Online (Sandbox Code Playgroud)

像这样使用来访问数据.

obj.name; // gives you "testing"
Run Code Online (Sandbox Code Playgroud)

只要键是唯一的,您就可以为对象提供几个逗号分隔的键/值对.

var obj = {name: "testing",
           another: "some other value",
           "a-key": "needed quotes because of the hyphen"
          };
Run Code Online (Sandbox Code Playgroud)

您还可以使用方括号来访问对象的属性.

在这种情况下需要这样做"a-key".

obj["a-key"] // gives you "needed quotes because of the hyphen"
Run Code Online (Sandbox Code Playgroud)

使用方括号,可以使用存储在变量中的属性名称来访问值.

var some_variable = "name";

obj[ some_variable ] // gives you "testing"
Run Code Online (Sandbox Code Playgroud)