【问题标题】:Conditionally rendering an Array Method using Ternary Operator使用三元运算符有条件地渲染数组方法
【发布时间】:2021-12-08 09:54:55
【问题描述】:

这是一个奇怪的情况,但使用三元运算符来确定我的数组方法将允许更多干燥代码。

目标:

const result = array. (isTrue ? some : every) (item) => {A lot of logic}

上面的代码显然行不通,但我想看看是否有一些语法允许这样的事情?

【问题讨论】:

  • 您需要更详细地描述您在此处尝试完成的任务。结果代表什么?您尝试使用三元运算符评估什么条件?

标签: javascript arrays reactjs methods conditional-operator


【解决方案1】:

您可以使用bracket notation 有条件地访问该方法:

const method = (isTrue, array) => array[isTrue ? 'some' : 'every'](item => item)

const arr = [0, 1, 2]

console.log(method(true, arr)) 
console.log(method(false, arr))

【讨论】:

  • 我想过这个,但我对缩小不够熟悉,不知道这是否会在激进缩小下崩溃?
  • 据我所知缩小不会改变字符串值和对象方法。
  • 我觉得可能是这样,谢谢你让我知道
【解决方案2】:

我会这样做:

const myLogic = (item) => { a lot of logic };

const result = isTrue ? array.some(myLogic) : array.every(myLogic)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多