簡體   English   中英

有/沒有大括號有什么區別?

[英]What is the difference with/without curly brackets?

我看到了一個源代碼,注意到a.name周圍有一個“額外的”大括號,如下所示,盡管我通常看到的常見情況是沒有大括號。 我想知道這在某些特定情況下會有所不同,但我嘗試過並得出相同的結果,或者某種約定。 有人知道區別嗎?

帶大括號

array.forEach((item, index) => {
  let a = {
    id: index;
  };

  {
    a.name = 'test';
  }
}

不帶大括號

array.forEach((item, index) => {
  let a = {
    id: index;
  };
  
  a.name = 'test';
}

在這種情況下,這兩個示例都是相同的,但是在其他情況下它有兩種用途。

一種用途是強制使用let聲明的變量的 scope 。 let變量是“塊作用域”,如果你在這樣的“塊”內聲明它們,那么它們將被限定為該塊。 例如:

let cookies = "Cookies are nice";

console.log(cookies);// "Cookies are nice"

{
    let cookies = "Cookies are nice";
}

console.log(cookies);// Reference error

The other use for them is simply to force auto-indenting to have an extra indent in your IDE... For example, most IDEs do not auto-indent PHP code, and some programmers will chose to use these blocks to fake out the IDE進入自動縮進。

例如:

<?php

//the code in here won't be auto-indented

?>

<?php
{
    //if I do this, then it will be auto-indented.
}
?>

希望這能回答你的問題。 :)

編輯:實際上,我相信在提到對象時這些括號還有另一種用途。 我見過他們用{ nameOfObject }代替nameOfObject ,但我不確切知道他們在這些情況下做了什么,也不能就此事發表意見。 我敢打賭這里的其他人可以回答這個問題,(如果你知道,請隨時發表評論分享原因!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM