gpt4 book ai didi

javascript - 使用 JS linter/formatter 将条件(else/if)运算符转换为逻辑运算符(&& ||)?

转载 作者:行者123 更新时间:2023-11-30 19:41:47 24 4
gpt4 key购买 nike

我有一些使用大量条件的旧 React 代码,例如使用 LET 设置变量,然后使用 if/else 来应用值。

为了可读性,我想将其更改为在有意义的地方使用逻辑运算符。

是否有可以自动执行此操作的 linter/格式化程序?

包含示例代码。

目前还不能用 ESlint 或 prettier 做到这一点。

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

用linter,自动转换成

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

如果存在可以自动重构它的格式化程序/插件/linter,请告诉我

最佳答案

您可以先检查play,然后再选择问题部分或答案部分。

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

要获得定义的假值,您可以添加一个默认值,例如 undefined

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

关于javascript - 使用 JS linter/formatter 将条件(else/if)运算符转换为逻辑运算符(&& ||)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com