我看到了源代码,并注意到有一个"附加的";在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
声明的变量的作用域。let
变量是"块作用域"的,如果你在一个"块"中声明它们;像这样,它们将被限定在那个块的范围内。例如:
let cookies = "Cookies are nice";
console.log(cookies);// "Cookies are nice"
,
{
let cookies = "Cookies are nice";
}
console.log(cookies);// Reference error
它们的另一个用途是强制自动缩进,以便在IDE中有额外的缩进…例如,大多数IDE不自动缩进PHP代码,一些程序员会选择使用这些块将IDE变成自动缩进。
例如:
<?php
//the code in here won't be auto-indented
?>
,
<?php
{
//if I do this, then it will be auto-indented.
}
?>