函数的JavaScript参数内的大括号括号

问题描述 投票:27回答:4

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

var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
javascript function parameters curly-braces
4个回答
34
投票

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

所以这:

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"

98
投票

自从提出这个问题以来,出现了第二个可能的答案。 Javascript ES6引入了Destructuring Assignment

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

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

x(y)


Result: "Good bye"

2
投票

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 

这将评估'标题;

这是将配置传递给方法的常用技术,这就是这里发生的事情。

© www.soinside.com 2019 - 2024. All rights reserved.