【发布时间】:2019-03-24 19:55:58
【问题描述】:
我又回来了。我有一个小问题,我可以在函数的 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 条件中声明变量。
提前谢谢你。 ~问
【问题讨论】:
标签: javascript function if-statement return