gpt4 book ai didi

javascript - 为什么允许独立代码块?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:18 25 4
gpt4 key购买 nike

我最近被 bug 咬了。我有这样的代码:

if (x == 1)
{
do_stuff();
}
else
{
do_other_stuff();
}

但是,我错误地省略了 else 这个词,所以第二个代码块总是被执行。

允许这样的独立代码块的理由是什么?我认为这是有充分理由的。

最佳答案

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

The block is delimited by a pair of curly brackets and may optionally be labelled (meaning it can be used with break or continue statements)

此外,它允许使用 letconst

block 范围变量

var x = 'Function scope'; {
let x = 'Block Scope';
console.log(x);
}

console.log(x);

引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block

关于javascript - 为什么允许独立代码块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com