1

如何正确纠正此语法:

if (tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m]) == ("null" || "undefined") {

...

}

(检查前 3 个变量中的任何一个是否为空或未定义)

4

7 回答 7

3

您可以定义一个小的帮助函数来进行检查,然后在所有值上使用它:

function notset(v) {
   return (v === undefined) || (v === null);
}

if (notset(tipoTropaPrioritaria[m]) || notset(troopsCount[m]) ||
    notset(availableTroops[m])) {
  ...
}
于 2010-05-24T21:15:41.453 回答
2

利用:

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}) {
于 2010-05-24T21:11:10.840 回答
1

这是做你想做的最好的方式

if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m]) {
    ...
}

运算符将!结果强制转换为可以测试的布尔值(null 和 undefined 变为 false),并且!前面false的 被否定true

另一种方法是针对nulland测试每个表达式undefined

function isNullOrUndefined(val) {
    return (val === null || typeof val == "undefined"); 
}    

if (isNullOrUndefined(a) || isNullOrUndefined(b) ... ) {

所以你知道,测试未定义的正确方法是

if (typeof foo === "undefined") {...
于 2010-05-24T21:12:14.897 回答
1

做法是:

if ((tipoTropaPrioritaria[m] == null || tipoTropaPrioritaria[m] == undefined)
|| (troopsCount[m] == null || troopsCount[m] == undefined) ||
(availableTroops[m] == null || availableTroops[m] == undefined)) {
...
}
于 2010-05-24T21:13:42.267 回答
1

如果你经常这样做,你可以创建一个辅助函数

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]))
  ...
于 2010-05-24T21:16:42.483 回答
0

如果您想检查它们是否为空或未定义,您可以编写

if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m])

两者都为null并且undefined错误的值。那么只有当这些都不是nullundefined时才会如此。请考虑还有其他错误值:

  • 0
  • 空字符串
于 2010-05-24T23:00:40.880 回答
0
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. */ }
于 2010-05-24T21:13:23.330 回答