我看到了源代码,注意到周围有一个“附加”大括号a.name,如下所示,尽管我通常看到的常见情况是没有大括号的。我想知道在某些特定情况下这会有所不同,但我尝试过并得出相同的结果,或者某种约定。有人知道其中的区别吗?
带大括号
array.forEach((item, index) => {
let a = {
id: index;
};
{
a.name = 'test';
}
}
Run Code Online (Sandbox Code Playgroud)
不带大括号
array.forEach((item, index) => {
let a = {
id: index;
};
a.name = 'test';
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,两个示例是相同的,但是,它在其他情况下有两种用途。
一种用途是强制使用 声明的变量的范围let。let变量是“块作用域”的,如果您在像这样的“块”内声明它们,那么它们的作用域将是该块。例如:
let cookies = "Cookies are nice";
console.log(cookies);// "Cookies are nice"
Run Code Online (Sandbox Code Playgroud)
但
{
let cookies = "Cookies are nice";
}
console.log(cookies);// Reference error
Run Code Online (Sandbox Code Playgroud)
它们的另一个用途就是强制自动缩进,以便在 IDE 中产生额外的缩进...例如,大多数 IDE 不会自动缩进 PHP 代码,并且一些程序员会选择使用这些块来伪造 IDE进入自动缩进。
例如:
<?php
//the code in here won't be auto-indented
?>
Run Code Online (Sandbox Code Playgroud)
但
<?php
{
//if I do this, then it will be auto-indented.
}
?>
Run Code Online (Sandbox Code Playgroud)