将变量声明为
const要求您立即将其指向一个值,并且此引用不能更改。
表示您无法在某个位置(之外
try)进行定义,而在其他位置(内)为其赋值
try。
const test; // Syntax Errortry { test = 5;} catch(err) {}另一方面,在
try块内创建它并为其赋值都很好。
try { const test = 5; // this is fine} catch(err) {}但是,它
const是块范围的,就像一样
let,因此,如果您确实在
try块中创建它并为其提供值,则它将仅存在于该范围内。
try { const test = 5; // this is fine} catch(err) {}console.log(test); // test doesn't exist here因此,如果您需要在之外访问此变量,则
try必须使用
let:
let configPath;try { configPath = path.resolve(process.cwd(), config);} catch(error) { //..... }console.log(configPath);另外,尽管可能更令人困惑,但是您可以使用
var在内创建变量,
try然后在变量外使用变量,因为
var它的作用范围是函数而不是块(并被提升):
try { var configPath = path.resolve(process.cwd(), config);} catch(error) { //..... }console.log(configPath);


