function ObjToSource(o){
if (!o) return 'null';
var k="",na=typeof(o.length)=="undefined"?1:0,str="";
for(var p in o){
if (na) k = "'"+p+ "':";
if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
else str += k + o[p] + ",";
}
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
/**
* @param variable mixed The var to log to the console
* @param varName string Optional, will appear as a label before the var
*/
function dd(variable, varName) {
var varNameOutput;
varName = varName || '';
varNameOutput = varName ? varName + ':' : '';
console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}
// Recursive print of object
var print = function( o, maxLevel, level ) {
if ( typeof level == "undefined" ) {
level = 0;
}
if ( typeof level == "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>';
}
var levelStr = '';
for ( var x = 0; x < level; x++ ) {
levelStr += ' ';
}
if ( maxLevel != 0 && level >= maxLevel ) {
str += levelStr + '...</br>';
return str;
}
for ( var p in o ) {
if ( typeof o[p] == 'string' ) {
str += levelStr +
p + ': ' + o[p] + ' </br>';
} else {
str += levelStr +
p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
}
}
// 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>';
}
return str;
};
用法:
var pagewilsObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
// Recursive of whole object
$('body').append( print(pagewilsObject) );
// Recursive of myObject up to 1 level, will only show name
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) );
var gandalf = {
"real name": "Gandalf",
"age (est)": 11000,
"race": "Maia",
"haveRetirementPlan": true,
"aliases": [
"Greyhame",
"Stormcrow",
"Mithrandir",
"Gandalf the Grey",
"Gandalf the White"
]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
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;
};
30 回答
(这已添加到我的图书馆GitHub)
在这里重新发明轮子!这些解决方案都不适用于我的情况 . 所以,我很快就抄写了pagewil的答案 . 这个不是用于打印到屏幕(通过控制台,或文本字段或其他) . 然而,它是用于数据传输的 . 此版本似乎返回与
toSource()
非常相似的结果 . 我没试过JSON.stringify
,但我认为这是一回事 . 此函数的结果是有效的Javascript对象声明 .我不会怀疑这样的事情是否已经出现在某个地方,但它只是缩短了时间而不是花一些时间来搜索过去的答案 . 而且当我开始搜索这个问题时,这个问题是谷歌的热门话题 . 我认为把它放在这里可能会帮助别人 .
无论如何,此函数的结果将是对象的字符串表示形式,即使您的对象具有嵌入的对象和数组,即使这些对象或数组具有更多嵌入的对象和数组 . (我听说你喜欢喝酒?所以,我用冷却器给你的车拉了个屁 . 然后,我用冷却器给你的冷却器拉了个屁 . 所以,你的冷却器可以喝,而你很酷 . )
数组与
[]
而不是{}
一起存储,因此没有键/值对,只有值 . 像常规数组一样 . 因此,它们像数组一样被创建 .此外,引用了所有字符串(包括键名),除非这些字符串具有特殊字符(如空格或斜杠),否则不需要这样做 . 但是,我不想检测到这只是为了删除一些原本仍能正常工作的报价 .
然后,此结果字符串可以与
eval
一起使用,或者只是将其转储到var thru字符串操作中 . 因此,从文本中重新创建对象 .让我知道如果我搞砸了,我的测试工作正常 . 此外,我能想到检测类型
array
的唯一方法是检查是否存在length
. 因为Javascript确实将数组存储为对象,所以我实际上无法检查类型array
(没有这样的类型!) . 如果其他人知道更好的方式,我很乐意听到它 . 因为,如果您的对象也有一个名为length
的属性,那么此函数会错误地将其视为数组 .编辑:添加了对空值对象的检查 . 谢谢Brock Adams
编辑:下面是固定功能,可以打印无限递归对象 . 这与FF的
toSource
打印不同,因为toSource
将打印无限递归一次,此时此函数将立即将其终止 . 这个函数比上面的那个运行得慢,所以我在这里添加它而不是编辑上面的函数,因为如果你计划传递链接回自己的对象,它只需要它 .测试:
结果:
注意:尝试打印
document.body
是一个可怕的例子 . 首先,FF在使用toSource
时只打印一个空对象字符串 . 使用上述功能时,FF会在SecurityError: The operation is insecure.
上崩溃 . Chrome将在Uncaught RangeError: Maximum call stack size exceeded
崩溃 . 显然,document.body
并不意味着转换为字符串 . 因为它要么太大,要么违反安全策略来访问某些属性 . 除非,我搞砸了一些东西,告诉我!这是功能 .
它可以使用带有可读性的制表符缩进来显示对象 .
Function:
Usage:
Example:
http://jsfiddle.net/WilsonPage/6eqMn/
我总是在我的项目中使用一个小辅助函数,通过控制台进行简单,快速的调试 . 从Laravel采取的灵感 .
Usage
dd(123.55);
输出:假设对象
obj = {0:'John', 1:'Foo', 2:'Bar'}
打印对象的内容
控制台输出(Chrome DevTools):
希望有所帮助!
其中
object
是你的对象或者你可以在chrome dev工具,“console”选项卡中使用它:
console.log(object);
我需要一种递归打印对象的方法,提供了pagewil的答案(谢谢!) . 我更新了一点,包括一种打印到某个级别的方法,并添加间距,以便根据我们当前的级别正确缩进,以便它更具可读性 .
用法:
在NodeJS中,您可以使用util.inspect(obj)打印对象 . 请务必说明深度,否则您只能打印浅物体 .
Javascript Function
Printing Object
通过print_r in Javascript
使用本机
JSON.stringify
方法 . 适用于嵌套对象和所有主流浏览器support此方法 .链接到Mozilla API Reference和其他示例 .
如果遇到此Javascript错误,请使用自定义JSON.stringify replacer
正如之前所说的最好,最简单的方式我找到了
如果您希望以表格格式查看数据,则可以使用
如果单击表列,则可以对表进行排序 .
您还可以选择要显示的列:
您可以找到有关console.table here的更多信息 .
可能你正在寻找这个
console.dir()
我认为最好的解决方案是查看对象的键,然后通过Object的值,如果你真的想看看对象的内容......
如果您使用ECMAScript 2016或更新版本,还有这个新选项:
console.dir(object)
:请注意,
console.dir()
功能是非标准功能 . 见MDN Web Docs如果你想打印它的全长物体,可以使用
如果要通过将对象转换为字符串来打印对象
这是一种方法:
With Firefox
如果您想打印对象以进行调试,我建议您安装Firebug for Firefox并使用以下代码:
With Chrome
会显示
注意:您只能记录对象 . 例如,这不起作用:
最简单的方法:
或者留言:
传递的第一个对象可以包含一个或多个格式说明符 . 格式说明符由百分号(%)后跟一个表示要应用的格式的字母组成 .
More format specifiers
试试这个:
这将打印对象的stringify版本 . 因此,您将获得对象的内容,而不是
[object]
作为输出 .使用带有颜色作为奖励的Node.js打印完整对象:
颜色当然是可选的,'depth:null'将打印整个对象 .
浏览器似乎不支持这些选项 .
参考文献:
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://nodejs.org/api/console.html#console_console_dir_obj_options
在控制台中显示对象的另一种方法是
JSON.stringify
. 查看以下示例:如果你正在寻找可以返回任何javascript对象的美化字符串的东西,请查看https://github.com/fresheneesz/beautinator . 一个例子:
结果是:
如果你的对象中有函数,它甚至可以工作 .
我总是使用
console.log("object will be: ", obj, obj1)
. 这样我就不需要使用带有JSON的stringify来解决这个问题 . 对象的所有属性都将很好地扩展 .我使用了pagewil的打印方法,它工作得非常好 .
这是我稍微扩展的版本,带有(草率)缩进和不同的prop / ob分隔符:
用这个:
如果要使用警报,要打印对象,可以执行以下操作:
alert("myObject is " + myObject.toSource());
它应该以字符串格式打印每个属性及其对应的值 .
pagewils代码的另一个修改...他不打印除字符串以外的任何内容,并将数字和布尔字段留空,我修复了由megaboss创建的函数内部的第二种类型的拼写错误 .
好吧,Firefox(感谢@Bojangles获取详细信息)有Object.toSource()方法,它将对象打印为JSON和
function(){}
.我想这对于大多数调试来说已经足够了 .