javascriptでオブジェクトの中身を見るときはconsole.log()を使ってパパっと表示させると思います。
Chromeのjavascriptコンソールは高機能なので、複雑な構造のオブジェクトもマウスでポチポチすれば中身を見ることができます。
一方、Node.jsでconsole.log()を使ってオブジェクトの中身を表示させようとすると、深い階層にあるプロパティが表示されません。
試しにやってみると以下のようになります(コメントアウトしてある部分が表示結果です)。
”yamada”と”ueda”が”Object”って省略されちゃってますね・・・
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Person = function(_name){ | |
this.name = _name; | |
this.friends = []; | |
}; | |
var obj = new Person("ore"); | |
obj.friends.push(new Person("satou")); | |
obj.friends[0].friends.push(new Person("yamada")); | |
obj.friends[0].friends.push(new Person("ueda")); | |
console.log(obj); | |
console.dir(obj); | |
/* | |
{ name: 'ore', | |
friends: [ { name: 'satou', friends: [Object] } ] } | |
*/ |
全てのプロパティを表示する方法は無いものかと探してみるとutilというモジュールの中にinspect()という関数がありました。
詳細はここに書いてあるので省きますが、こいつを使えば全てのプロパティが表示できそうです。
ということで、試した見たのが以下のコードになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Person = function(_name){ | |
this.name = _name; | |
this.friends = []; | |
}; | |
var obj = new Person("ore"); | |
obj.friends.push(new Person("satou")); | |
obj.friends[0].friends.push(new Person("yamada")); | |
obj.friends[0].friends.push(new Person("ueda")); | |
var util = require('util'); | |
console.log(util.inspect(obj,false,null)); | |
/* | |
{ name: 'ore', | |
friends: | |
[ { name: 'satou', | |
friends: | |
[ { name: 'yamada', friends: [] }, | |
{ name: 'ueda', friends: [] } ] } ] } | |
*/ |
0 件のコメント:
コメントを投稿