如何正确纠正此语法:
if (tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m]) == ("null" || "undefined") {
...
}
(检查前 3 个变量中的任何一个是否为空或未定义)
如何正确纠正此语法:
if (tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m]) == ("null" || "undefined") {
...
}
(检查前 3 个变量中的任何一个是否为空或未定义)
您可以定义一个小的帮助函数来进行检查,然后在所有值上使用它:
function notset(v) {
return (v === undefined) || (v === null);
}
if (notset(tipoTropaPrioritaria[m]) || notset(troopsCount[m]) ||
notset(availableTroops[m])) {
...
}
利用:
if (tipoTropaPrioritaria[m] == null || troopsCount[m] == null || availableTroops[m] == null ||
tipoTropaPrioritaria[m] == undefined || troopsCount[m] == undefined || availableTroops[m] == undefined) {
// ...
}
编辑===
:在这种情况下使用 (threequals) 运算符可能会更好。
if (tipoTropaPrioritaria[m] === null || troopsCount[m] === null || availableTroops[m] === null ||
tipoTropaPrioritaria[m] === undefined || troopsCount[m] === undefined || availableTroops[m] === undefined) {
// ...
}
或者:
if (null in {tipoTropaPrioritaria[m]:0, troopsCount[m]:0, availableTroops[m]:0} || undefined in {tipoTropaPrioritaria[m]:0, troopsCount[m]:0, availableTroops[m]:0}) {
这是做你想做的最好的方式
if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m]) {
...
}
运算符将!
结果强制转换为可以测试的布尔值(null 和 undefined 变为 false),并且!
前面false
的 被否定true
。
另一种方法是针对null
and测试每个表达式undefined
。
function isNullOrUndefined(val) {
return (val === null || typeof val == "undefined");
}
if (isNullOrUndefined(a) || isNullOrUndefined(b) ... ) {
所以你知道,测试未定义的正确方法是
if (typeof foo === "undefined") {...
做法是:
if ((tipoTropaPrioritaria[m] == null || tipoTropaPrioritaria[m] == undefined)
|| (troopsCount[m] == null || troopsCount[m] == undefined) ||
(availableTroops[m] == null || availableTroops[m] == undefined)) {
...
}
如果你经常这样做,你可以创建一个辅助函数
function isNullOrUndef(args) {
for (var i =0; i < arguments.length; i++) {
if (arguments[i] == null || typeof arguments[i] === "undefined") {
return true
}
}
return false
}
if (isNullOrUndef(tipoTropaPrioritaria[m], troopsCount[m], availableTroops[m]))
...
如果您想检查它们是否为空或未定义,您可以编写
if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m])
两者都为null并且undefined
是错误的值。那么只有当这些都不是null或undefined时才会如此。请考虑还有其他错误值:
if (tipoTropaPrioritaria[m] && troopsCount[m] && availableTroops[m]) { }
else { /* At least ones is undefined/null OR FALSE */ }
if (tipoTropaPrioritaria[m] == null || troopsCount[m] == null || availableTroops[m] == null)
{ /* One is null. */ }