这个 If 语句能否用一行写出来?
这个 If 语句能否用一行写出来?
已关闭。这个问题需要细节或清晰。目前它不接受回答。
想要改进这个问题?通过编辑此帖子添加详细信息并澄清问题。
改善此问题
有没有一行代码的方法可以根据布尔值执行一次if语句?
var boolean; if (!boolean) { function doSomething(); boolean = true; }
大概是这样。
admin 更改状态以发布 2023年5月23日
将代码写成一行并没有太多意义,因为你已经写得很清楚(除了语法错误),但是它是可以实现的。
function test(myBool) { function doSomething () { console.log('run'); } myBool = myBool || doSomething() || true; console.log(myBool); } test(false); test(true);
或者,如果doSomething返回true布尔值或truthy值:
function test(myBool) { function doSomething () { console.log('run'); return true; } myBool = myBool || doSomething(); console.log(myBool); } test(false); test(true);