【问题标题】:Javascript: error Unnecessary use of boolean literals in conditional expression no-unneeded-ternaryJavascript:错误在条件表达式中不必要地使用布尔文字 no-unneeded-ternary
【发布时间】:2020-08-19 19:46:31
【问题描述】:

我是 javascript 新手,我似乎无法解决我遇到的一个小问题。我到处寻找,尝试了许多其他选择,但似乎没有任何效果。 此功能工作正常,但我收到此错误消息:

error  Unnecessary use of boolean literals in conditional expression  no-unneeded-ternary

这是我的代码:

const valid = (email) => {
  // TODO: return true if the `email` string has the right pattern!
  const match = (email.match(/^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/) ? true : false);
  return match;
};

任何人都知道我如何以不同的方式写这个吗?预先感谢您的帮助! 奥利维尔

【问题讨论】:

  • 三元将其转换为布尔值。这比只在比赛中返回布尔值更慢,更耗费认知

标签: javascript regex email if-statement conditional-operator


【解决方案1】:

您可以使用返回布尔值的RegExp#test

const valid = email => /^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/.test(email);

【讨论】:

  • 谢谢,这更有意义。我遇到了这个 .test 函数,但并不真正知道如何使用它。谢谢!
【解决方案2】:

condition ? true : false; 真的很奇怪

使用Boolean(condition)!!condition

转换为布尔类型

const valid = (email) => {
    // TODO: return true if the `email` string has the right pattern!
    const match = email.match(/^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/);
    return Boolean(match);
};

【讨论】:

  • 此方法将始终返回 true,这里的转换不是问题。 String.prototype.match() 返回一个数组
  • no @RobertMennell - 如果没有找到匹配项,则返回 null - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 啊,很好,我对空电话有点困惑。谢谢你
  • 谢谢你们解决我的问题,我很感激。另一个有用的答复是,很难决定授予谁正式答复。
  • @OlivierGirardot 问题主题是关于错误的布尔转换类型,但绝对没有转换是最好的转换;)
猜你喜欢
  • 2017-07-31
  • 2016-06-12
  • 2018-09-14
  • 2020-12-15
  • 2018-10-02
  • 2017-08-25
  • 2018-07-28
  • 2012-06-19
  • 1970-01-01
相关资源
最近更新 更多