【问题标题】:Curly braces inside JavaScript arguments for functions函数的 JavaScript 参数中的花括号
【发布时间】:2011-05-08 00:20:26
【问题描述】:

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

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

【问题讨论】:

    标签: javascript function arguments curly-braces


    【解决方案1】:

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

    var x = function({ foo }) {
       console.log(foo)
    }
    
    var y = {
      bar: "hello",
      foo: "Good bye"
    }
    
    x(y)
    
    
    Result: "Good bye"
    

    【讨论】:

    • 非常感谢。这正是我一直在寻找的答案。 More here.
    • 这实际上是正确的答案,因为问题是“函数”。
    • 这就是答案
    • 多么简洁的答案,赞!一直在阅读很多答案,但所有人都在用复杂的可能答案陈述技术术语。做得好 。谢谢
    【解决方案2】:

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

    所以这个:

    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 了解更多详情。

      【讨论】:

        【解决方案4】:
        var x = {title: 'the title'};
        

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

        x.title 
        

        这将评估为'标题;

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

        【讨论】:

          猜你喜欢
          • 2016-10-09
          • 1970-01-01
          • 2020-11-13
          • 2019-02-16
          • 2013-08-10
          • 2016-05-28
          • 1970-01-01
          • 2011-08-20
          相关资源
          最近更新 更多