JavaScript typeofとundefinedを使用してオブジェクトがあるかの確認サンプル

環境
Windows 10 Home 64bit
Google Chrome 107.0.5304.107

構文
const オブジェクト名 = {プロパティ名:値}
if (typeof オブジェクト === “undefined")
typeofとundefinedを使用してオブジェクトがあるかの確認します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const user = {
name: "yamada",
};
if (typeof user === "undefined") {
console.log("userオブジェクトが存在しない true");
}else{
console.log("userオブジェクトが存在する false");
}
if (typeof age === "undefined") {
console.log("ageオブジェクトが存在しない true");
} else {
console.log("ageオブジェクトが存在する false");
}
const user = { name: "yamada", }; if (typeof user === "undefined") { console.log("userオブジェクトが存在しない true"); }else{ console.log("userオブジェクトが存在する false"); } if (typeof age === "undefined") { console.log("ageオブジェクトが存在しない true"); } else { console.log("ageオブジェクトが存在する false"); }
const user = {
   name: "yamada",
 };

 if (typeof user === "undefined") {
   console.log("userオブジェクトが存在しない true");
 }else{
   console.log("userオブジェクトが存在する false"); 
 }

 if (typeof age === "undefined") {
   console.log("ageオブジェクトが存在しない true"); 
 } else {
   console.log("ageオブジェクトが存在する false");
 }

実行結果
> “userオブジェクトが存在する false"
> “ageオブジェクトが存在しない true"

JavaScript

Posted by arkgame