我想看看JavaScript对象的结构(用于调试)。PHP中有类似var_dump的东西吗?
当前回答
在JavaScript中等效的var_dump ?很简单,没有。
但这并不意味着你就无能为力了。就像一些人建议的那样,使用Firebug(或其他浏览器中的等效工具),但与其他人建议的不同的是,当你有(稍微)更好的工具console.dir时,不要使用console.log:
console.dir(object)
打印对象的所有属性的交互式列表。这 看起来与您在DOM选项卡中看到的视图相同。
其他回答
你也可以试试这个函数。我不记得原作者了,但所有功劳都归他们。
工作就像一个魅力- 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));
我写了这个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;
}
我提出这一点是为了帮助那些需要实用的东西的人,给你一个漂亮的、美化的(缩进的)JS节点的图片。对于节点,没有其他解决方案适合我(“周期性错误”或其他什么…)。这将引导您遍历DOM Node下的树(不使用递归),并为您提供深度、tagName(如果适用)和textContent(如果适用)。
在头节点下走过树时遇到的任何其他节点细节都可以根据自己的兴趣添加……
function printRNode( node ){
// make sort of human-readable picture of the node... a bit like PHP print_r
if( node === undefined || node === null ){
throwError( 'node was ' + typeof node );
}
let s = '';
// NB walkDOM could be made into a utility function which you could
// call with one or more callback functions as parameters...
function walkDOM( headNode ){
const stack = [ headNode ];
const depthCountDowns = [ 1 ];
while (stack.length > 0) {
const node = stack.pop();
const depth = depthCountDowns.length - 1;
// TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
s += ' '.repeat( depth ) + stringRep + '\n';
const lastIndex = depthCountDowns.length - 1;
depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
if( node.childNodes.length ){
depthCountDowns.push( node.childNodes.length );
stack.push( ... Array.from( node.childNodes ).reverse() );
}
while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
depthCountDowns.splice( -1 );
}
}
}
walkDOM( node );
return s;
}
最常见的方式:
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
我希望这对你有帮助:-)
Firebug。
然后,在javascript中:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
现在你可以查看控制台,点击语句,看看里面有什么
推荐文章
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError:
- [].slice的解释。调用javascript?
- jQuery日期/时间选择器
- 合并两个PHP对象的最佳方法是什么?
- 我如何预填充一个jQuery Datepicker文本框与今天的日期?
- 数组的indexOf函数和findIndex函数的区别
- jQuery添加必要的输入字段