我想看看JavaScript对象的结构(用于调试)。PHP中有类似var_dump的东西吗?
当前回答
我写了这个JS函数dump()来像PHP的var_dump()一样工作。 要在警报窗口中显示变量的内容:dump(variable) 要在网页中显示变量的内容: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;
}
其他回答
Firebug。
然后,在javascript中:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
现在你可以查看控制台,点击语句,看看里面有什么
最常见的方式:
console.log(object);
但是我必须提到JSON。Stringify用于转储非浏览器脚本中的变量:
console.log( JSON.stringify(object) );
JSON。正如Simon Zyx指出的那样,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
我希望这对你有帮助:-)
在JavaScript中等效的var_dump ?很简单,没有。
但这并不意味着你就无能为力了。就像一些人建议的那样,使用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;
}
你也可以试试这个函数。我不记得原作者了,但所有功劳都归他们。
工作就像一个魅力- 100%相同的var_dump在PHP。
来看看。
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));
推荐文章
- 检测用户何时离开网页的最佳方法?
- 当“模糊”事件发生时,我如何才能找到哪个元素的焦点去了*到*?
- React不会加载本地图像
- 如何将Blob转换为JavaScript文件
- 在另一个js文件中调用JavaScript函数
- 如何在svg元素中使用z索引?
- 如何求一个数的长度?
- 跨源请求头(CORS)与PHP头
- 如何用Express/Node以编程方式发送404响应?
- parseInt(null, 24) === 23…等等,什么?
- JavaScript变量声明在循环外还是循环内?
- super()失败,错误:TypeError "参数1必须是类型,而不是classobj"当父不继承对象
- 元素在“for(…in…)”循环中排序
- 在哪里放置JavaScript在HTML文件?
- 什么时候.then(success, fail)被认为是承诺的反模式?