函数的 JavaScript 参数内的花括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4146984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:29:45  来源:igfitidea点击:

Curly braces inside JavaScript parameters for functions

javascriptfunctionparameterscurly-braces

提问by milan

What do the curly braces surrounding JavaScript parameters for functions do?

函数的 JavaScript 参数周围的花括号有什么作用?

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

采纳答案by user113716

The curly braces denote an object literal. It is a way of sending key/value pairs of data.

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

So this:

所以这:

var obj = {name: "testing"};

Is used like this to access the data.

像这样用来访问数据。

obj.name; // gives you "testing"

You can give the object several comma separated key/value pairs, as long as the keys are unique.

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

var obj = {name: "testing",
           another: "some other value",
           "a-key": "needed quotes because of the hyphen"
          };

You can also use square brackets to access the properties of the object.

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

This would be required in the case of the "a-key".

"a-key".

obj["a-key"] // gives you "needed quotes because of the hyphen"

Using the square brackets, you can access a value using a property name stored in a variable.

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

var some_variable = "name";

obj[ some_variable ] // gives you "testing"

回答by Matthias Winkelmann

A second possible answerhas arisen since this question was asked. Javascript ES6introduced Destructuring Assignment.

一个第二个可能的答案已经出现,因为这问题有人问。Javascript ES6引入了解构赋值

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

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

x(y)


Result: "Good bye"

回答by camomilk

Curly braces in javascript are used as shorthand to create objects. For example:

javascript 中的花括号用作创建对象的速记。例如:

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

Check out Douglas Crockford's JavaScript Surveyfor more detail.

查看 Douglas Crockford 的JavaScript 调查了解更多详情。

回答by hvgotcodes

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

defines an object literal that has properties on it. you can do

定义一个具有属性的对象字面量。你可以做

x.title 

which will evaluate to 'the title;

这将评估为'标题;

this is a common technique for passing configurations to methods, which is what is going on here.

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