LoginSignup
12
10

More than 5 years have passed since last update.

jsオブジェクト存在チェック

Last updated at Posted at 2014-06-26

オブジェクト存在チェック

if-in

var hoge = {aa : 'good'};
if ('aa' in hoge) {}
var myObj = {a: 1, b: 2, c: 3}, myKeys = [], i=0;
for (myKeys[i++] in myObj);
console.log(myKeys);

上記のやり方は賢いw、以下のリンクをご参照
Exploring JavaScript for-in loops

hasOwnProperty()

obj.hasOwnProperty();

上記の違いは以下のストックをご参照
in と hasOwnProperty() の違い

注意点

for .. inの場合はhasOwnPropertyの判断を入れた方が安全、原因は

Some frameworks (e.g. Prototype.js and Mootools) add a lot of custom prototype augmentation and using for-in to iterate Arrays and Strings is generally considered a bad idea. Using a regular for loop is a good alternative for Array and String iteration. In addition, ES5 defines a bunch of custom Array iterators (forEach, map etc). Unfortunately non of these alternate iteration strategies work with regular Objects – which is why its considered very bad practice to augment Object.prototype.

例:

var arr = ['a','b','c'], indexes = [];
Array.prototype.each = function() {/*blah*/};

for (var index in arr) {
    indexes.push(index);
}

indexes; //["0", "1", "2", "each"] whoops!

if

var hoge = {aa : 'good'};
if (hoge['aa'])

ifもfor .. inと同じくhasOwnPropertyで判断必要あり

結論

Arrayの場合はfor文かArray.forEach(every,some)で使うベキ
Objectの場合はfor .. in + hasOwnPropertyでやる

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10