有没有一种方法可以使用 ES6 语法在一行中控制台日志/错误并从函数返回?

问题描述 投票:0回答:1

我发现自己编写了很多类似于以下的代码:

const fileEl = document.getElementById("import-style-file-input");
if (fileEl === null) {
   console.error("No file element");
   return;
}

有没有办法可以将第 3 行和第 4 行压缩为一行?例如

if (fileEl === null) log_and_return("No file element");

或者范围限制使得这变得不可能?

ecmascript-6 syntax
1个回答
0
投票

因为

return;
本身只是返回
undefined
,所以你可以返回
console.error
的结果,这也是
undefined
:

if (fileEl === null) return console.error("No file element");
© www.soinside.com 2019 - 2024. All rights reserved.