react,简化三元表达式?

代码如下:

{[ntgls, ytgls, stgls].filter(item => item == '(苹果)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(雪梨)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(香蕉)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(橙子)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(火龙果)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(西瓜)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(柚子)').length >= 2 || [ntgls, ytgls, stgls].filter(item => item == '(山竹)').length >= 2 ? <span>以下特点比较显著:<br /></span> : null}

如果继续使用以上的写法和格式,请问可否将其简化?请在现有代码基础上展示说明。

const fruits = ['(苹果)', '(雪梨)', '(香蕉)', '(橙子)', '(火龙果)', '(西瓜)', '(柚子)', '(山竹)']
const arr = [ntgls, ytgls, stgls]
fruits.some(f => arr.filter(i => i == f).length >= 2) ? ... : ...
  • 数组的some()方法替代多个或者运算符

    jsx
    {[ntgls, ytgls, stgls].some(arr => 
    arr.filter(item => item == '(苹果)').length >= 2 ||
    arr.filter(item => item == '(雪梨)').length >= 2 ||
    // ...
    ) ? <span>以下特点比较显著:<br /></span> : null}
    
  • 对象映射替代三元表达式

{
  let fruitCount = {
    '(苹果)': [ntgls, ytgls, stgls].filter(item => item == '(苹果)').length,
    '(雪梨)': [ntgls, ytgls, stgls].filter(item => item == '(雪梨)').length,
    // ...
  }
  let content = Object.values(fruitCount).some(c => c >= 2) 
  ? <span>以下特点比较显著:<br /></span> : null; 
  content  
}

望采纳!

可以使用数组的some方法来简化这个三元表达式。some方法可以遍历数组中的元素,如果有任意一个元素满足指定的条件函数,则返回true,否则返回false

具体实现可以将数组中所有的水果名称作为一个数组fruits,然后使用some方法遍历这个数组,判断是否存在某种水果出现了两次及以上。如果满足条件,则返回需要渲染的 JSX 元素,否则返回 null

代码如下:

const fruits = ['(苹果)', '(雪梨)', '(香蕉)', '(橙子)', '(火龙果)', '(西瓜)', '(柚子)', '(山竹)'];

{fruits.some(fruit => [ntgls, ytgls, stgls].filter(item => item === fruit).length >= 2) ? <span>以下特点比较显著:<br /></span> : null}

这样就可以将原来的冗长的三元表达式简化成一行代码,易于维护和阅读。