【发布时间】:2012-01-03 09:56:49
【问题描述】:
这是我如何提到两个条件,如果这个或这个
if (Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
【问题讨论】:
标签: javascript
这是我如何提到两个条件,如果这个或这个
if (Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
【问题讨论】:
标签: javascript
只需将它们添加到 if 语句的主括号中,如
if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
从逻辑上讲,这也可以以更好的方式重写! 意思完全一样
if (Type == 2 && (PageCount == 0 || PageCount == '')) {
【讨论】:
这是另一种方法。
const conditionsArray = [
condition1,
condition2,
condition3,
]
if (conditionsArray.indexOf(false) === -1) {
"do somthing"
}
或者 ES7+
if (!conditionsArray.includes(false)) {
"do somthing"
}
【讨论】:
&& 运算符,如果您不想在if 中编写长/多行条件,请将其放在变量下。
我目前正在检查大量条件,使用 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
}
【讨论】:
AND而不是OR的另一种写法。
整个if 应该用括号括起来,or 运算符是|| 而不是!!,所以
if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) { ...
【讨论】:
有时您可以找到进一步组合语句的技巧。
例如:
0 + 0 = 0
和
"" + 0 = 0
所以
PageCount == 0
PageCount == ''
可以写成:
PageCount+0 == 0
在 javascript 中,0 与 false 反转 ! 一样好,它会将 0 变成 true
!PageCount+0
总计:
if ( Type == 2 && !PageCount+0 ) PageCount = elm.value;
【讨论】:
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
这可能是一种可能的解决方案,所以“或”是||不是 !!
【讨论】:
用一对额外的括号把它们包起来,你就可以走了。
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
【讨论】:
function go(type, pageCount) {
if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
}
}
【讨论】:
或运算符
if ( con1 == True || con2 == True || con3 == True){
// statement ...
}
AND 运算符
if ( con1 == True && con2 == True && con3 == True){
// statement ...
}
我的作品:D
【讨论】:
如果你有很多条件并且你想在only 一个 条件语句中添加它们,那么你可以将条件添加到一个数组,然后像这样构造条件语句:
const c = [
true,
false,
true,
true,
false,
true
];
if(c[0] || c[1] || c[2] || c[3] || c[4] || c[5]){
document.write('YES, it satisfies ONE or MORE conditions.');
}else{
document.write('NO conditions have been satisfied.');
}
if(c[0] && c[1] && c[2] && c[3] && c[4] && c[5]){
console.log('YES, it satisfies ALL conditions');
}else{
console.log('It does NOT satisfy ALL conditions');
}
【讨论】: