在三元运算符中执行函数[重复](Execute function in ternary operator [duplicate])

这个问题在这里已有答案:

为什么JSHint不喜欢对象的方法调用三元组? 3个答案

我正在使用JSHint检查我的JS文件以查找错误。

我刚收到这个警告:

期望一个赋值或函数调用,而是看到一个表达式。

(mandatEngagementExists) ? $('.mandat-type[value=1]').prop('checked', false).prop('disabled', true) : $('.mandat-type[value=1]').prop('disabled', false);

mandatEngagementExists是一个布尔值。 我所有的JS都处于严格模式。

这段代码正在运行,所以我想知道JSHint是否有点过于严格,或者我是否应该切换到经典的if / else。

This question already has an answer here:

Why does JSHint dislike ternaries for method calls on objects? 3 answers

I'm checking my JS files using JSHint to find mistakes.

I just got this warning :

Expected an assignment or function call and instead saw an expression.

(mandatEngagementExists) ? $('.mandat-type[value=1]').prop('checked', false).prop('disabled', true) : $('.mandat-type[value=1]').prop('disabled', false);

mandatEngagementExists is a boolean. All my JS is in strict mode.

This piece of code is working so I wanted to know if JSHint was a bit too strict or if I should switch to a classic if/else.

最满意答案

直接在.prop("property", boolean)使用boolean

$(el).prop('checked', myBoolean);

使用return

function myFn() { /* Code here */ return myBoolean ? $(el).doThis() : $(el).doThat(); /* !!!!!!!!! >>> Cannot have more code here since `return` was used */ }

使用IIFE

function myFn() { /* Code here */ (function(){ return myBoolean? $(el).doThis() : $(el).doThat(); }()); /* Code here */ }

使用var

var someVar; function myFn() { /* Code here */ someVar = myBoolean? $(el).doThis() : $(el).doThat(); /* Code here */ }

使用if else

function myFn() { /* Code here */ if(myBoolean) { $(el).doThis(); } else { $(el).doThat(); } /* Code here */ }

use boolean directly inside the .prop("property", boolean)

$(el).prop('checked', myBoolean);

Using return

function myFn() { /* Code here */ return myBoolean ? $(el).doThis() : $(el).doThat(); /* !!!!!!!!! >>> Cannot have more code here since `return` was used */ }

Using an IIFE

function myFn() { /* Code here */ (function(){ return myBoolean? $(el).doThis() : $(el).doThat(); }()); /* Code here */ }

Using var

var someVar; function myFn() { /* Code here */ someVar = myBoolean? $(el).doThis() : $(el).doThat(); /* Code here */ }

Using if else

function myFn() { /* Code here */ if(myBoolean) { $(el).doThis(); } else { $(el).doThat(); } /* Code here */ }

更多推荐