オブジェクトのプロパティの存在確認方法メモ
1.単純に obj.property で確認すると・・・
var obj = {}; if (obj.hoge) alert('not exist'); obj.hoge = false; if (obj.hoge) alert('exist false'); obj.hoge = null; if (obj.hoge) alert('exist null'); obj.hoge = undefined; if (obj.hoge) alert('exist undefined'); obj.hoge = ""; if (obj.hoge) alert('exist ""'); obj.hoge = 0; if (obj.hoge) alert('exist 0'); obj.hoge = NaN; if (obj.hoge) alert('exist NaN');
1番上のif以外は、hogeプロパティが存在しているので、
alert が表示されて欲しいが、1つも出ない
2.undefined かどうかで判定
基本的に、プロパティが存在しない場合には undefined が返ってくるので、
var obj = {}; alert(typeof obj.hoge); // "undefined"
「undefined でない」イコール「プロパティが存在している」とするのであれば、
var obj = {}; if (obj.hoge !== undefined) alert('not exist'); obj.hoge = false; if (obj.hoge !== undefined) alert('exist false'); obj.hoge = null; if (obj.hoge !== undefined) alert('exist null'); obj.hoge = undefined; if (obj.hoge !== undefined) alert('exist undefined'); obj.hoge = ""; if (obj.hoge !== undefined) alert('exist ""'); obj.hoge = 0; if (obj.hoge !== undefined) alert('exist 0'); obj.hoge = NaN; if (obj.hoge !== undefined) alert('exist NaN');
これで、false, null, "", 0, NaN を値として取るプロパティも判定可能
(typeof obj.hoge !== "undefined" でもOK)
ただ、当然ながら undefined を値として取るプロパティは判定不可能
3.undefined を値として取るプロパティも判定
var obj = {}; if ("hoge" in obj) alert('not exist'); obj.hoge = false; if ("hoge" in obj) alert('exist false'); obj.hoge = null; if ("hoge" in obj) alert('exist null'); obj.hoge = undefined; if ("hoge" in obj) alert('exist undefined'); obj.hoge = ""; if ("hoge" in obj) alert('exist ""'); obj.hoge = 0; if ("hoge" in obj) alert('exist 0'); obj.hoge = NaN; if ("hoge" in obj) alert('exist NaN');
とすると、false, null, undefined, "", 0, NaN の存在確認が可能
4.おまけ
2の例で「!==」ではなく「!=」とすると、
var obj = {}; if (obj.hoge != undefined) alert('not exist'); obj.hoge = false; if (obj.hoge != undefined) alert('exist false'); obj.hoge = null; if (obj.hoge != undefined) alert('exist null'); obj.hoge = undefined; if (obj.hoge != undefined) alert('exist undefined'); obj.hoge = ""; if (obj.hoge != undefined) alert('exist ""'); obj.hoge = 0; if (obj.hoge != undefined) alert('exist 0'); obj.hoge = NaN; if (obj.hoge != undefined) alert('exist NaN');
null が外れて、false, "", 0, NaN のみになる