2010-11-10 103 views

回答

28

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

所以这个:

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" 
+0

谢谢你,非常有帮助! – milan 2010-11-10 17:49:39

+0

@user - 不客气。 :o) – user113716 2010-11-10 18:07:53

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

限定其上具有属性的对象文字。你可以做

x.title 

这将评估'的标题;

这是一种将配置传递给方法的常用技巧,这就是发生在这里的原因。

2

javascript中的大括号用作创建对象的简写形式。例如:

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

退房道格拉斯Crockford的JavaScript Survey了解更多详情。

61

一个第二个可能的答案已经出现,因为这问题有人问。 Javascript ES6介绍Destructuring Assignment

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

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

x(y) 


Result: "Good bye" 
+9

非常感谢。这正是我正在寻找的答案。 [更多信息](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – FuzzY 2015-12-11 07:30:40