【问题标题】:javascript return the checking value if condition matches, otherwise another value如果条件匹配,javascript返回检查值,否则返回另一个值
【发布时间】:2018-06-03 18:39:25
【问题描述】:

所以我想知道是否有一些类似于三元运算符的内置方法,但会返回真值检查的左值,如果为假则返回右值。

如果没有,我打算这样做(并澄清我的意思)

function myTernary(leftValue, operator, condition, rightValue) {
  let expression = `${leftValue} ${operator} ${condition}`
  let result = eval('('+expression+')')
  return result ? leftValue : rightValue
}

// leftValue is returned if the condition is truthy, otherwise rightValue

console.log(myTernary(1 + 2 + 3 + 4, "<", 12, 12))

eval 将在客户端执行,所以...应该没问题,因为客户端可以任意打开他们的 Web 控制台并输入他们想要的任何内容。

【问题讨论】:

  • leftValue === condition ? leftValue : rightValue 就是这样......
  • 你要then ? condition : otherwise吗?不,这是不可能的,只需重新排序操作数。
  • 如果您不使用eval,您的示例可能会更清晰。
  • @PatrickRoberts 我知道你可以做到。我只是有一个很大的表情,所以我只是想看看我是否可以节省空间。我有类似x + z + e + g &lt; 12 的东西,如果它们小于12,我只想返回x、z、e、g 的总和,否则在右侧,我也可以将总和移到另一个变量然后返回,但这只是一个奇怪的问题。
  • var q = x + z + e + g; return q &lt; 12 ? q : rightValue

标签: javascript ternary-operator


【解决方案1】:

您可以使用|| 运算符...

console.log(1!=2||5)
console.log(1==2||5)

【讨论】:

  • 好吧,我不想要真或假,我想要 ACTUAL 值。我将更改示例,使其实际上更清晰一些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2014-05-21
  • 1970-01-01
  • 2021-10-18
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多