如何使用三元语句来简化这段代码?

How can I use a ternary statement to simplify this code?

在我的第一个 if 语句中,它检查数组 foodwindow[items] 中的单词是否出现在文本中。在我的第二个 if 语句中,它检查数组 window[items] 中的单词是否出现在文本

请注意,哪个 if 语句是 运行 取决于数组 authors 是否为空 - 第一个语句将 运行 如果它不为空,第二个将运行如果为空。

if(food.length > 0 && food.some(text => tag.textContent.includes(text)) && window[items].some(text => tag.textContent.includes(text))) {
   ele[i].style.display = "block";
}else{
   ele[i].style.display = "none";  
}

if(food.length < 1 && window[items].some(text => tag.textContent.includes(text))) {
   ele[i].style.display = "block";
}else{
   ele[i].style.display = "none";  
}

我曾尝试使用三元运算符简化此代码,但 returns 出现此错误:

Uncaught SyntaxError: Unexpected token )

if((food.length > 0 ? food.some(text => tag.textContent.includes(text))) && window[items].some(text => tag.textContent.includes(text))) {
   ele[i].style.display = "block";
}else{
   ele[i].style.display = "none"; 
}

要使用三元运算符,您需要 ?:。伪代码:

if (condition) { block1 } else { block2 } => condition ? block1 : block2

条件:food.length > 0

区块 1:food.some(text => tag.textContent.includes(text)) && window[items].some(text => tag.textContent.includes(text))

区块 2:window[items].some(text => tag.textContent.includes(text))

所以这应该有效:

if (food.length > 0 ? food.some(text => tag.textContent.includes(text)) && window[items].some(text => tag.textContent.includes(text)) : window[items].some(text => tag.textContent.includes(text)))

你可以通过两个语句的累加并用或(||)条件来检查来实现。像

      ele[i].style.display = (food.length > 0 && food.some(text => tag.textContent.includes(text)) && window[items].some(text => 
      tag.textContent.includes(text)) || (food.length < 1 && 
      window[items].some(text => tag.textContent.includes(text))) ? "block" :"none"

但是对于新代码来说这看起来很糟糕 reader。为了队伍中的后辈,请坚持现在的方式?

所以,条件是:if (food 为空 or 标签文本包含 food) and 标签文本包含任何 window[items] :

ele[i].style.display = (!food.length || food.some(text => tag.textContent.includes(text)))
          && window[items].some(text => tag.textContent.includes(text)) ? "block" : "none";