如何在JavaScript中的if语句中指定多个条件


87

这就是我提到这两个条件的方式

if (Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')
    PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

Answers:


154

只需将它们添加到if语句的主括号内,例如

if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
            PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

从逻辑上讲,也可以用更好的方式重写它!这具有完全相同的含义

if (Type == 2 && (PageCount == 0 || PageCount == '')) {

1
同意。也没有条件的花括号。那无济于事。
塔斯(Tass)2015年

26

这是一种替代方法。

const conditionsArray = [
    condition1, 
    condition2,
    condition3,
]

if (conditionsArray.indexOf(false) === -1) {
    "do somthing"
}

或ES6

if (!conditionsArray.includes(false)) {
   "do somthing"
}

19

我当前正在检查大量条件,使用if语句方法超出上述4个条件将变得笨拙。只是为了给将来的观众分享一个干净的替代方案...可以很好地扩展,我使用:

var a = 0;
var b = 0;

a += ("condition 1")? 1 : 0; b += 1;
a += ("condition 2")? 1 : 0; b += 1;
a += ("condition 3")? 1 : 0; b += 1;
a += ("condition 4")? 1 : 0; b += 1;
a += ("condition 5")? 1 : 0; b += 1;
a += ("condition 6")? 1 : 0; b += 1;
// etc etc

if(a == b) {
    //do stuff
}

1
我没有评论说这是不明智的做法,因此我认为这样做是省钱的。谢谢!
CousinCocaine

2
值得一提的是,这仅在所有条件都必须为真时才有效。换句话说,这是另一种书写方式,AND但不是OR
Mark Kramer


6

有时,您可以找到技巧来进一步组合语句。

例如:

0 + 0 = 0

"" + 0 = 0

所以

PageCount == 0
PageCount == ''

可以这样写:

PageCount+0 == 0

在javascript0中,与false!其转换0true

!PageCount+0

总计:

if ( Type == 2 && !PageCount+0 ) PageCount = elm.value;

这是如果您要使代码尽可能短,但是它与许多良好做法背道而驰。保持代码可读性。这个答案是含糊的,会诱使下一个查看您的代码的人犯一些错误。
belvederef

4
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {

        PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

这可能是可能的解决方案之一,因此“或”为||。不!


3

将它们包裹在一对额外的paren中,您就可以开始了。

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
    PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

-1
function go(type, pageCount) {
    if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
        pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
    }
}

请缩进您的代码,如果您不够自信,请不要回答问题。
Harshit
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.