我又回来了。我有一个小问题,关于我是否可以在函数的 IF 条件中声明一个变量,并在语句本身中使用它。
好吧,我很好奇是否有一种方法可以在 IF 语句的条件内声明变量,并在语句中进一步使用该变量,如下所示:
function SomeFunc() {return true}
if (let n = SomeFunc()) {
console.log(n); // true
// n is truthy
} else {
// Would never run, because it always returns true.
// This is just an example though, where it can return a truthy or falsy value dependent on the input context I could give it.
console.log(n); // false (if it actually returned 'false')
// n is falsy
}
有什么方法可以做到这一点,而不必运行该函数两次并且不在 IF 语句之外运行它?
(但不是这样的):
let n = SomeFunc();
if (n) { ... } else { ... }
// Or this:
if (SomeFunc()) {
let n = SomeFunc();
} else { ... }
我希望在条件内声明一个函数,以最大限度地减少行的使用并使其 - 对我来说 - 干净。我希望有一种方法可以在 IF 条件内声明变量。
提前谢谢您。 〜问
最佳答案
该语法不允许 let
、const
或 var
出现在该位置。
但是您可以只定义变量(无需初始化),然后执行 if
:
let n;
if (n = SomeFunc()) {
// n is truthy
} else {
// n is falsy
}
如果您想将该变量的范围限制为 if
,则将其放入 block 中:
// other code...
{
let n;
if (n = SomeFunc()) {
// n is truthy
} else {
// n is falsy
}
}
// other code...
当然,如果您的函数没有其他代码,则不需要额外的 block :将应用函数的 block 。
许多人会不同意您的观点,即 if
条件内的赋值是干净的。最佳实践是避免在某种情况下出现此类副作用,尽管对此有不同的看法。尽管如此,如下所示并不需要更多的字符,而且对我来说看起来更干净:
{
let n = SomeFunc();
if (n) {
// n is truthy
} else {
// n is falsy
}
}
作为函数表达式
另一种方法是使用立即调用的函数表达式,您可以向该表达式提供函数的返回值作为参数:
(n => {
if (n) {
// n is truthy
} else {
// n is falsy
}
})(SomeFunc());
关于javascript - 可以在 IF 语句中从函数声明变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327965/