場合によっては、JavaScriptが次のステップで処理するために、特定の変数に依存して「定義する」または「存在する」必要がある場合があります。
”
typeof
“は可変データ型をチェックするのに便利な演算子です。
typeof演算子によって返される値のリストを次に示します。
-
“number” – 変数は数値です.
-
“string” – 変数は文字列です.
-
“ブール値” – 変数はブール値です.
-
“オブジェクト” – 変数はオブジェクトです.
-
null – 変数はnullです.
-
“未定義” – 変数が定義されていません.
したがって、この場合、変数が存在するかどうかを調べるには、 ”
typeof
“演算子を使用し、戻り値が ”
undefined
“であるかどうかを確認してください。
1. typeof == “undefined”
変数が定義されているかどうかをチェックするための
` typeof
“の使用方法を示す完全なHTMLの例。
<html>
<body>
<h1>JavaScript : typeof example</h1>
<script type="text/javascript">
var str1 = "mkyong.com";
if(typeof str1 == 'string'){
document.write(str1 + " is a string <br/>");
}
if(typeof str1 == 'undefined'){
document.write("str1 variable is not exists <br/>");
}else{
document.write("str1 variable is exists <br/>");
}
if(typeof str2 == 'undefined'){
document.write("str2 variable is not exists <br/>");
}else{
document.write("str2 variable is exists <br/>");
}
</script>
</body>
</html>
デモ
Webブラウザ上でHTMLファイルの上に開くと、次の結果が返されます。
mkyong.com is a string str1 variable is exists str2 variable is not exists
ソースコードをダウンロードする
ダウンロードする – リンク://wp-content/uploads/2011/11/typeof-example-check-if-variable-is-defined.zip[typeof-example-check-if-variable-is-defined.zip]( 1 KB)