1

この構文を正しく修正する方法:

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

...

}

(最初の 3 つの変数のいずれかが null または未定義であるかどうかを確認するため)

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ます。

nullそれを行うもう 1 つの方法は、各式をandに対してテストすることですundefined

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

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

ご存じのとおり、undefined をテストする正しい方法は次のとおりです。

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]) { }
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 に答える
0

それらがnullまたは未定義であるかどうかを確認したい場合は、次のように書くことができます

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

nullfalseundefinedの値の両方です。次に、これがnullまたはundefinedでない場合にのみ true になります。他にも誤った値があることを考慮してください。

  • 0
  • 空の文字列
  • NaN
于 2010-05-24T23:00:40.880 に答える