32
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

for in文とfor文 

Last updated at Posted at 2014-08-31

for in文だとプロトタイプチェーン上のプロパティまで列挙されてしまう
そのため、自身のプロパティだけを判別して列挙するためにはtypeofまたはhasOwnPropertyを使います

for_in.js
//typeofを用いた場合
for (name in obj) {
    if (typeof(obj[name]) !== 'function') {
        console.log(name+'は自身のプロパティです');
    }
}

//hasOwnPropertyを用いた場合
for (name in obj) {
    if(obj.hasOwnProperty(name)) {
        console.log(name+'は自身のプロパティです');
    }
}

しかし、for文だと

配列の場合

for.js
for (i=0; i<arr.length; i++) {
    var name=i;
    console.log(name+'は自身のプロパティです');
}

とシンプルにかける。

オブジェクトの場合、underscorejsを用いると簡単にできます

for_obj.js
var obj = {
    id     : 1,
    name   : 'Tanaka',
    age    : 23,
    living : true,
    birthday : '1998/12/24'
};

_.reduce(obj, function(result, value, key){
    console.log(key+'は、自身のプロパティです');
    console.log('値は、'+value+'です');
    return 0;
},0);

以上、お役に立てれば幸いです。

32
31
1

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
32
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?