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

时间:2018-01-01 16:44:05

标签: javascript ternary-operator

在我的第一个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";  
}

我尝试使用三元运算符来简化此代码,但它会返回此错误:

  

Uncaught SyntaxError:意外的令牌)

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"; 
}

3 个答案:

答案 0 :(得分:2)

您可以通过累积两个语句并使用OR(||)条件进行检查来实现它。像

这样的东西
      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"

但对于新的代码阅读器而言,这看起来很糟糕。为了团队中的青少年,请坚持当前的方式吗?

答案 1 :(得分:1)

因此,条件是:if {food为空标记文本包含food中的任何一个,标记文本包含任何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"; 

答案 2 :(得分:0)

要拥有三元运算符,您需要?:。伪代码:

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)))