这个 If 语句可以写在一行中吗?
Can this If statement be written in one line?
是否有一种单行方式来执行仅使用布尔值触发一次的 if 语句?
var boolean;
if (!boolean) {
function doSomething();
boolean = true;
}
这里面有些东西。
将其作为一行完成没有多大意义,因为代码按照您编写的方式很清楚(减去语法错误),但可以完成
function test(myBool) {
function doSomething () { console.log('run'); }
myBool = myBool || doSomething() || true;
console.log(myBool);
}
test(false);
test(true);
或者如果 doSomething returns 是一个真布尔值或真值
function test(myBool) {
function doSomething () { console.log('run'); return true; }
myBool = myBool || doSomething();
console.log(myBool);
}
test(false);
test(true);
你可以坐logical OR assignment ||=
with a comma operator.
boolean ||= (doSomething(), true);
是否有一种单行方式来执行仅使用布尔值触发一次的 if 语句?
var boolean;
if (!boolean) {
function doSomething();
boolean = true;
}
这里面有些东西。
将其作为一行完成没有多大意义,因为代码按照您编写的方式很清楚(减去语法错误),但可以完成
function test(myBool) {
function doSomething () { console.log('run'); }
myBool = myBool || doSomething() || true;
console.log(myBool);
}
test(false);
test(true);
或者如果 doSomething returns 是一个真布尔值或真值
function test(myBool) {
function doSomething () { console.log('run'); return true; }
myBool = myBool || doSomething();
console.log(myBool);
}
test(false);
test(true);
你可以坐logical OR assignment ||=
with a comma operator.
boolean ||= (doSomething(), true);