【问题标题】:how to convert if else statement to ternary operators如何将 if else 语句转换为三元运算符
【发布时间】:2018-10-25 14:22:41
【问题描述】:

如何将以下 javascript 代码重写为 ES6 版本:

if(allUser[currentUser]['email']==email){
        if(allUser[currentUser]['password']==password){
            isUserFound = true
            passwordCorrect = true 
            break
        } else {
            isUserFound = true
            passwordCorrect = false
            break
        }
    } else {
        isUserFound = false
    }

【问题讨论】:

  • 什么是“ES6 版本”?三元运算符从一开始就存在于该语言中。
  • (foo['email'] == email && foo['password'] == password) ? isUserFound, passwordCorrect = true : isUserFound, passwordCorrect = false;
  • 另外,只是一个小小的题外话:请不要养成在行尾省略分号;的习惯,这只会带来麻烦。
  • @Xufox 感谢您指出错字。为了帮助OP,三元语法:if_evaluation_block ? true_condition_block_OR_another_ternary_block_here : else_condition_block_OR_another_ternary_block_here
  • @Rikin,你能帮我写下这段代码吗?

标签: javascript ecmascript-6 ternary-operator


【解决方案1】:

这是个坏主意,您的代码使用if/else 更具可读性。您可以简化为:

isUserFound = allUser[currentUser]['email'] === email;
passwordCorrect = isUserFound && allUser[currentUser]['password'] == password

如果您不知道,breakif 也没有影响,只有forwhileswitch

【讨论】:

  • 我假设break 在一个循环中。上面写着currentUserisUserFound,暗示 OP 循环遍历许多用户以找到特定的用户。也许,这可以用find 写,这可能是 OP 对“ES6”的意思。
猜你喜欢
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 2016-05-22
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多