在我的第一个if语句中,它检查文本中是否出现来自数组food
和window[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";
}
我尝试使用三元运算符来简化此代码,但它返回此错误:
未捕获的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";
}
所以,条件是: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";
您可以通过累积两个语句并使用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"
但对于新的代码阅读器而言,这看起来很糟糕。为了团队中的青少年,请坚持目前的方式吗?
要有三元运算符,你需要?
和:
。伪代码:
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))
第二组: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)))