この構文を正しく修正する方法:
if (tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m]) == ("null" || "undefined") {
...
}
(最初の 3 つの変数のいずれかが null または未定義であるかどうかを確認するため)
この構文を正しく修正する方法:
if (tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m]) == ("null" || "undefined") {
...
}
(最初の 3 つの変数のいずれかが null または未定義であるかどうかを確認するため)
チェックを行う小さなヘルパー関数を定義し、それをすべての値で使用できます。
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
それを行うもう 1 つの方法は、各式をandに対してテストすることですundefined
。
function isNullOrUndefined(val) {
return (val === null || typeof val == "undefined");
}
if (isNullOrUndefined(a) || isNullOrUndefined(b) ... ) {
ご存じのとおり、undefined をテストする正しい方法は次のとおりです。
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]) { }
else { /* At least ones is undefined/null OR FALSE */ }
if (tipoTropaPrioritaria[m] == null || troopsCount[m] == null || availableTroops[m] == null)
{ /* One is null. */ }
それらがnullまたは未定義であるかどうかを確認したい場合は、次のように書くことができます
if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m])
nullとfalseundefined
の値の両方です。次に、これがnullまたはundefinedでない場合にのみ true になります。他にも誤った値があることを考慮してください。