オブジェクトの構造をJavaScriptで見たい(デバッグ用)。PHP の var_dump に似たものはありますか?
9 に答える
最新のブラウザーのほとんどには、開発者ツールにコンソールがあり、この種のデバッグに役立ちます。
console.log(myvar);
次に、オブジェクトの適切にマッピングされたインターフェイス/コンソール内のものを取得します。
詳細については、console
ドキュメントを参照してください。
最も一般的な方法:
console.log(object);
ただしJSON.stringify
、ブラウザー以外のスクリプトで変数をダンプするのに役立つものは次のとおりです。
console.log( JSON.stringify(object) );
Simon ZyxJSON.stringify
が指摘したように、この関数は組み込みの整形もサポートしています。
例:
var obj = {x: 1, y: 2, z: 3};
console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2
上記のスニペットは次のように出力されます。
{
"x": 1,
"y": 2,
"z": 3
}
caniuse.comでは、この機能をネイティブにサポートするブラウザーを表示できますJSON.stringify
: http://caniuse.com/json
Douglas Crockford ライブラリを使用して、JSON.stringify
古いブラウザーのサポートを追加することもできます: https://github.com/douglascrockford/JSON-js
ドキュメントJSON.stringify
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
これが役立つことを願っています:-)
この JS 関数dump()
は、PHP の のように動作するように記述しvar_dump()
ました。アラート ウィンドウに変数のdump(variable)
内容を表示するには: Web ページに変数の内容を表示するにはdump(variable, 'body')
: 変数の文字列を取得するには:dump(variable, 'none')
/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
out = '';
for (var i = 0; i < num; i++) {
out += str;
}
return out;
}
/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
v: The variable
howDisplay: "none", "body", "alert" (default)
recursionLevel: Number of times the function has recursed when entering nested
objects or arrays. Each level of recursion adds extra space to the
output to indicate level. Set to 0 by default.
Return Value:
A string of the variable's contents
Limitations:
Can't pass an undefined variable to dump().
dump() can't distinguish between int and float.
dump() can't tell the original variable type of a member variable of an object.
These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;
var vType = typeof v;
var out = vType;
switch (vType) {
case "number":
/* there is absolutely no way in JS to distinguish 2 from 2.0
so 'number' is the best that you can do. The following doesn't work:
var er = /^[0-9]+$/;
if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
out = 'int';
}
*/
break;
case "boolean":
out += ": " + v;
break;
case "string":
out += "(" + v.length + '): "' + v + '"';
break;
case "object":
//check if null
if (v === null) {
out = "null";
}
//If using jQuery: if ($.isArray(v))
//If using IE: if (isArray(v))
//this should work for all browsers according to the ECMAScript standard:
else if (Object.prototype.toString.call(v) === '[object Array]') {
out = 'array(' + v.length + '): {\n';
for (var i = 0; i < v.length; i++) {
out += repeatString(' ', recursionLevel) + " [" + i + "]: " +
dump(v[i], "none", recursionLevel + 1) + "\n";
}
out += repeatString(' ', recursionLevel) + "}";
}
else {
//if object
let sContents = "{\n";
let cnt = 0;
for (var member in v) {
//No way to know the original data type of member, since JS
//always converts it to a string and no other way to parse objects.
sContents += repeatString(' ', recursionLevel) + " " + member +
": " + dump(v[member], "none", recursionLevel + 1) + "\n";
cnt++;
}
sContents += repeatString(' ', recursionLevel) + "}";
out += "(" + cnt + "): " + sContents;
}
break;
default:
out = v;
break;
}
if (howDisplay == 'body') {
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
else if (howDisplay == 'alert') {
alert(out);
}
return out;
}
JavaScript の var_dump に相当するものは? 単純に、1つもありません。
しかし、それはあなたが無力のままになっているという意味ではありません。一部の人が提案したように、Firebug (または他のブラウザーで同等のもの) を使用しますが、他の人が提案したものとは異なり、(わずかに) 優れたツールconsole.dirがある場合は console.log を使用しないでください。
console.dir(object)
オブジェクトのすべてのプロパティのインタラクティブなリストを出力します。これは、DOM タブに表示されるビューと同じように見えます。
JSON 応答を HTML に解析するための優れたシンプルなソリューション。
var json_response = jQuery.parseJSON(data);
html_response += 'JSON Response:<br />';
jQuery.each(json_response, function(k, v) {
html_response += outputJSONReponse(k, v);
});
function outputJSONReponse(k, v) {
var html_response = k + ': ';
if(jQuery.isArray(v) || jQuery.isPlainObject(v)) {
jQuery.each(v, function(j, w) {
html_response += outputJSONReponse(j, w);
});
} else {
html_response += v + '<br />';
}
return html_response;
}
この機能を試すこともできます。元の作者を思い出せませんが、すべてのクレジットは彼/彼女に帰属します。
魔法のように動作します - PHP の var_dump と 100% 同じです。
見てみな。
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
// Example:
var employees = [
{ id: '1', sex: 'm', city: 'Paris' },
{ id: '2', sex: 'f', city: 'London' },
{ id: '3', sex: 'f', city: 'New York' },
{ id: '4', sex: 'm', city: 'Moscow' },
{ id: '5', sex: 'm', city: 'Berlin' }
]
// Open dev console (F12) to see results:
console.log(dump(employees));