如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
试试看:
console.log(JSON.stringify(obj))
这将打印对象的字符串版本。因此,您将获得object的内容,而不是[object]作为输出。
其他回答
正如之前所说,我发现的最简单的方法是
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
pagewils代码的另一个修改。。。他不打印字符串以外的任何内容,并将数字和布尔字段留空,我修复了megaboss创建的函数内部第二种类型的拼写错误。
var print = function( o, maxLevel, level )
{
if ( typeof level == "undefined" )
{
level = 0;
}
if ( typeof maxlevel == "undefined" )
{
maxLevel = 0;
}
var str = '';
// Remove this if you don't want the pre tag, but make sure to remove
// the close pre tag on the bottom as well
if ( level == 0 )
{
str = '<pre>'; // can also be <pre>
}
var levelStr = '<br>';
for ( var x = 0; x < level; x++ )
{
levelStr += ' '; // all those spaces only work with <pre>
}
if ( maxLevel != 0 && level >= maxLevel )
{
str += levelStr + '...<br>';
return str;
}
for ( var p in o )
{
switch(typeof o[p])
{
case 'string':
case 'number': // .tostring() gets automatically applied
case 'boolean': // ditto
str += levelStr + p + ': ' + o[p] + ' <br>';
break;
case 'object': // this is where we become recursive
default:
str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
break;
}
}
// Remove this if you don't want the pre tag, but make sure to remove
// the open pre tag on the top as well
if ( level == 0 )
{
str += '</pre>'; // also can be </pre>
}
return str;
};
试试这个:
var object = this.window;
console.log(object,'this is window object');
输出:
看起来很简单。。。in无法解决这个问题,特别是当我们想要处理自定义、主机、本机或CSCOM对象之外的问题时。此外,我们正在讨论调试,谁知道我们何时何地需要它!
我的小型库可以处理以下对象:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
并呈现出丰富多彩的标识,如:
0,foo,'bar'0,loop2,'包含对索引0'0处的对象的循环引用,另一个,'object'1,a1,11,b1,'baz'1,loop1,'包含索引2'1,c1,'true'1,d1,''1,e1,[1,2]处的对象循环引用
但请看这里:
https://github.com/centurianii/jsdebughttp://jsfiddle.net/centurianii/92Cmk/36/
通过一些预防措施,甚至可以解析document.body!
假设对象obj={0:'John',1:'Foo',2:'Bar'}
打印对象的内容
for (var i in obj){
console.log(obj[i], i);
}
控制台输出(Chrome DevTools):
John 0
Foo 1
Bar 2
希望这有帮助!