ES6中,是否可以在严格模式下使用consttry{}中设置变量?

'use strict';

const path = require('path');

try {
    const configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....
}

console.log(configPath);

由于configPath的定义超出了范围,因此无法实现lint.唯一可行的方法是:

'use strict';

const path = require('path');

let configPath;
try {
    configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....   
}

console.log(configPath);

基本上,在这种情况下,有没有办法用const而不是let

推荐答案

将变量声明为const需要您立即将其指向一个值,并且此引用无法更改.

这意味着您不能在一个地方(try之外)定义它,并在其他地方(try之内)为它赋值.

const test; // Syntax Error
try {
  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);

或者,尽管可能更令人困惑,但您可以使用vartry中创建变量,并在其外部使用它,因为var的作用域在函数中,而不是块(并得到hoisted):

try {
   var configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....   
}

console.log(configPath);

Node.js相关问答推荐

我的位置也移动时左右拖动谷歌 map

如何在Node.js 中设置图表js的背景色

为什么在导出的函数中调用node-sqlite3中的数据库方法时不起作用?

Express无法发布

填充函数在Node.js和MongoDB中不起作用

我的 MERN 网站一直告诉我我的一个函数不是一个函数

如何在Node.js的telegraf.js命令中添加参数?

无法通过 NextJS 访问 HTTP 帖子中的正文

当其中一个端点不工作时,如何使用 axios.all() 调用多个 API?

使用正则表达式查找文档,但输入是数组

为什么我的 npm 脚本中的 glob 不起作用?

如何将使用 Gulp 的 node 部署到 heroku

搜索MongoDB条目的正确方法是'_id';在 node 中

Chrome 浏览器未将 if-modified-since 标头发送到服务器

我可以在 Heroku 中运行咖啡脚本吗?

nodejs v10.3.0 的 gulp 任务问题:src\node_contextify.cc:629: Assertion `args[1]->IsString()' failed

PhoneGap/Cordova Android 开发

将 Heroku App 连接到 Atlas MongoDB 云服务

找不到在 docker compose 环境中运行的 node js 应用程序的模块

用于轻松部署和更新的 Node.js 设置