简体   繁体   English

使用 JS linter/格式化程序将条件 (else/if) 运算符转换为逻辑运算符 (&& ||)?

[英]Convert conditional (else/if) operators to logical operators (&& ||) with a JS linter/formatter?

I have some older React code using a lot of conditionals, eg setting a variable using LET then if/else to apply a value.我有一些使用很多条件的较旧的 React 代码,例如使用 LET 设置变量然后 if/else 应用一个值。

For readability, I want to change it to use logical operators where it makes sense to do so.为了可读性,我想将其更改为在有意义的地方使用逻辑运算符。

Is there a linter / formatter that can do this automatically?是否有可以自动执行此操作的 linter / 格式化程序?

Example code included.包括示例代码。

Cannot do it so far with ESlint or prettier so far.到目前为止还不能用 ESlint 或者更漂亮的来做到这一点。

let method
if (play && play.show_question) method = 'question'
else if (play && play.show_answer) method = 'answer'

with a linter, automatically convert to使用 linter,自动转换为

const method = play && play.show_question ? 'question' : play && play.show_answer && 'answer'

If a formatter / plugin / linter exists which can auto refactor this, please let me know如果存在可以自动重构的格式化程序/插件/linter,请告诉我

You could check play first and then take either the question part or answer part.您可以先检查play ,然后再进行问题部分或答案部分。

const method = play && (play.show_question && 'question' || play.show_answer && 'answer');

For getting a defined false value, you could add a default value, like undefined为了获得一个定义的假值,你可以添加一个默认值,比如undefined

const
    method = play && (play.show_question && 'question' || play.show_answer && 'answer')
        || undefined;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM