How do I display the content of a JavaScript object in a string format like when we alert
a variable?
如何以字符串形式显示JavaScript对象的内容,比如当我们警告变量时?
The same formatted way I want to display an object.
我想要显示一个对象的格式相同。
29 个解决方案
#1
710
If you want to print the object for debugging purposes, I suggest instead installing Firebug for Firefox and using the code:
如果您想为调试目的打印对象,我建议为Firefox安装Firebug并使用代码:
console.log(obj)
#2
1633
Use native JSON.stringify
method. Works with nested objects and all major browsers support this method.
使用原生JSON。stringify方法。使用嵌套对象和所有主流浏览器都支持这种方法。
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
Link to Mozilla API Reference and other examples.
链接到Mozilla API参考和其他示例。
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
Use a custom JSON.stringify replacer if you encounter this Javascript error
使用自定义JSON。如果遇到这个Javascript错误,stringify replacer。
"Uncaught TypeError: Converting circular structure to JSON"
#3
355
var output = '';
for (var property in object) {
output += property + ': ' + object[property]+'; ';
}
alert(output);
#4
87
console.dir(object)
:
console.dir(对象):
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
显示指定JavaScript对象的属性的交互列表。这个清单允许您使用信息公开三角形来检查子对象的内容。
Note that the console.dir()
feature is non-standard. See MDN Web Docs
注意,console.dir()特性是非标准的。看到MDN Web文档
#5
63
Well, Firefox (thanks to @Bojangles for detailed information) has Object.toSource()
method which prints objects as JSON and function(){}
.
嗯,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和函数(){}。
That's enough for most debugging purposes, I guess.
我想这对于大多数调试来说已经足够了。
#6
63
try this :
console.log(JSON.stringify(obj))
This will print the stringify version of object. So instead of [object]
as an output you will get the content of object.
这将打印对象的stringify版本。因此,您将获得对象的内容,而不是作为输出。
#7
50
If you want to use alert, to print your object, you can do this:
如果你想使用警告,打印你的对象,你可以这样做:
alert("myObject is " + myObject.toSource());
alert(“myObject”+ myObject. tosource ());
It should print each property and its corresponding value in string format.
它应该以字符串格式打印每个属性及其相应的值。
#8
31
Function:
功能:
var print = function(o){
var str='';
for(var p in o){
if(typeof o[p] == 'string'){
str+= p + ': ' + o[p]+'; </br>';
}else{
str+= p + ': { </br>' + print(o[p]) + '}';
}
}
return str;
}
Usage:
用法:
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
Example:
例子:
http://jsfiddle.net/WilsonPage/6eqMn/
http://jsfiddle.net/WilsonPage/6eqMn/
#9
28
In NodeJS you can print an object by using util.inspect(obj). Be sure to state the depth or you'll only have a shallow print of the object. http://nodejs.org/api/util.html#util_util_inspect_object_options
在node . js中,您可以通过使用util. inspection (obj)来打印一个对象。一定要说明深度,否则你只会有一个对象的浅打印。http://nodejs.org/api/util.html util_util_inspect_object_options
#10
26
If you would like to see data in tabular format you can use
如果您希望以表格格式查看数据,您可以使用。
console.table(obj);
Table can be sorted if you click on the table column.
如果单击表列,可以对表进行排序。
You can also select what columns to show:
您还可以选择要显示的列:
console.table(obj, ['firstName', 'lastName']);
You can find more information about console.table here
您可以找到更多关于控制台的信息。表
#11
18
As it was said before best and most simply way i found was
正如我之前所说的,我发现的最简单的方法就是。
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
#12
17
To print the full object with Node.js with colors as a bonus:
用节点打印完整对象。有颜色的js:
console.dir(object, {depth: null, colors: true})
Colors are of course optional, 'depth: null' will print the full object.
颜色当然是可选的,'depth: null'将打印完整的对象。
The options don't seem to be supported in browsers.
这些选项在浏览器中似乎不受支持。
References:
引用:
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://nodejs.org/api/console.html#console_console_dir_obj_options
https://nodejs.org/api/console.html console_console_dir_obj_options
#13
16
Use this:
用这个:
console.log('print object: ' + JSON.stringify(session));
#14
14
If you would like to print the object of its full length, can use
如果你想打印它的全部长度的对象,可以使用。
console.log(require('util').inspect(obj, {showHidden: false, depth: null})
console.log(要求(“跑龙套”)。检查(obj, {showHidden: false, depth: null})
If you want to print the object by converting it to the string then
如果您想要打印对象,请将其转换为字符串。
console.log(JSON.stringify(obj));
console.log(JSON.stringify(obj));
#15
11
I needed a way to recursively print the object, which pagewil's answer provided (Thanks!). I updated it a little bit to include a way to print up to a certain level, and to add spacing so that it is properly indented based on the current level that we are in so that it is more readable.
我需要一种递归打印对象的方法,这是pagewil的答案(谢谢!)我对它进行了一些更新,包括了一种打印到某个级别的方法,并添加了间距,这样它就可以根据当前的级别进行适当缩进,这样就更容易阅读了。
// 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;
};
Usage:
用法:
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) );
#16
9
(This has been added to my library at GitHub)
(这已经被添加到GitHub的我的库中)
Reinventing the wheel here! None of these solutions worked for my situation. So, I quickly doctored up pagewil's answer. This one is not for printing to screen (via console, or textfield or whatever). It is, however, for data transport. This version seems to return a very similar result as toSource()
. I've not tried JSON.stringify
, but I assume this is about the same thing. The result of this function is a valid Javascript object declaration.
重新发明*!这些解决方案都不能解决我的问题。所以,我迅速修改了pagewil的答案。这不是用于打印到屏幕(通过控制台,或textfield或其他什么)。然而,它是用于数据传输的。这个版本似乎返回了与toSource()非常相似的结果。我没有试过JSON。stringify,但是我假设这是一样的。该函数的结果是一个有效的Javascript对象声明。
I wouldn't doubt if something like this was already on SO somewhere, but it was just shorter to make it than to spend a while searching past answers. And since this question was my top hit on google when I started searching about this; I figured putting it here might help others.
我不怀疑这样的事情是否已经发生在某个地方,但它只是比花一段时间搜索过去的答案更短。因为这个问题是我在谷歌上搜索这个问题时的第一反应;我想把它放在这里可能会对其他人有所帮助。
Anyhow, the result from this function will be a string representation of your object, even if your object has embedded objects and arrays, and even if those objects or arrays have even further embedded objects and arrays. (I heard you like to drink? So, I pimped your car with a cooler. And then, I pimped your cooler with a cooler. So, your cooler can drink, while your being cool.)
无论如何,这个函数的结果将是对象的字符串表示,即使对象有嵌入对象和数组,即使这些对象或数组有更深入的嵌入对象和数组。我听说你喜欢喝酒?所以,我给你的车加了个冷气。然后,我用一个冷却器把你的冷却器拉平。所以,你的冷却器可以喝,而你的酷。
Arrays are stored with []
instead of {}
and thus dont have key/value pairs, just values. Like regular arrays. Therefore, they get created like arrays do.
数组被存储为[]而不是{},因此没有键/值对,只有值。像普通数组。因此,它们就像数组一样被创建。
Also, all string (including key names) are quoted, this is not necessary unless those strings have special characters (like a space or a slash). But, I didn't feel like detecting this just to remove some quotes that would otherwise still work fine.
此外,所有字符串(包括键名)都被引用,除非这些字符串有特殊字符(比如空格或斜杠),否则这是不必要的。但是,我不想仅仅是为了删除一些本来还可以正常工作的引号。
This resulting string can then be used with eval
or just dumping it into a var thru string manipulation. Thus, re-creating your object again, from text.
这个结果字符串可以与eval一起使用,或者直接将其转储到一个var thru字符串操作中。因此,从文本重新创建您的对象。
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)+"]";
}
Let me know if I messed it all up, works fine in my testing. Also, the only way I could think of to detect type array
was to check for the presence of length
. Because Javascript really stores arrays as objects, I cant actually check for type array
(there is no such type!). If anyone else knows a better way, I would love to hear it. Because, if your object also has a property named length
then this function will mistakenly treat it as an array.
如果我搞砸了,请告诉我,在我的测试中效果很好。另外,我想要检测类型数组的唯一方法是检查是否存在长度。因为Javascript真的将数组存储为对象,所以实际上我不能检查类型数组(没有这样的类型!)如果有人知道更好的方法,我很乐意听到。因为,如果您的对象也有一个名为length的属性,那么这个函数将错误地将其视为一个数组。
EDIT: Added check for null valued objects. Thanks Brock Adams
编辑:为空值对象添加检查。由于布鲁克亚当斯
EDIT: Below is the fixed function to be able to print infinitely recursive objects. This does not print the same as toSource
from FF because toSource
will print the infinite recursion one time, where as, this function will kill it immediately. This function runs slower than the one above, so I'm adding it here instead of editing the above function, as its only needed if you plan to pass objects that link back to themselves, somewhere.
编辑:下面是能够打印无限递归对象的固定函数。由于toSource将会打印无限递归,所以这个函数将会立即将其杀死。这个函数比上面的函数运行得慢,所以我将它添加到这里,而不是编辑上面的函数,因为它只需要如果您打算将链接返回到它们自己的对象,就需要在某个地方。
const ObjToSource=(o)=> {
if (!o) return null;
let str="",na=0,k,p;
if (typeof(o) == "object") {
if (!ObjToSource.check) ObjToSource.check = new Array();
for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
ObjToSource.check.push(o);
}
k="",na=typeof(o.length)=="undefined"?1:0;
for(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 (typeof(o) == "object") ObjToSource.check.pop();
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
Test:
测试:
var test1 = new Object();
test1.foo = 1;
test1.bar = 2;
var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;
console.log(ObjToSource(testobject));
console.log(testobject.toSource());
Result:
结果:
{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})
NOTE: Trying to print document.body
is a terrible example. For one, FF just prints an empty object string when using toSource
. And when using the function above, FF crashes on SecurityError: The operation is insecure.
. And Chrome will crash on Uncaught RangeError: Maximum call stack size exceeded
. Clearly, document.body
was not meant to be converted to string. Because its either too large, or against security policy to access certain properties. Unless, I messed something up here, do tell!
注意:尝试打印文档。身体就是一个可怕的例子。首先,FF只是在使用toSource时打印一个空的对象字符串。当使用上面的函数时,FF会在SecurityError上崩溃:操作是不安全的。而Chrome将会在未捕获的RangeError上崩溃:超过了最大的调用堆栈大小。显然,文档。身体不应该被转换成字符串。因为它要么太大,要么违反安全策略来访问某些属性。除非,我把事情搞砸了,告诉我!
#17
6
I always use console.log("object will be: ", obj, obj1)
. this way I don't need to do the workaround with stringify with JSON. All the properties of the object will be expanded nicely.
我总是使用控制台。log(“对象将是:”,obj, obj1)。这样我就不需要用JSON来处理stringify。对象的所有属性都将被很好地扩展。
#18
5
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
where object
is your object
对象是什么?
or you can use this in chrome dev tools, "console" tab:
或者你可以在chrome开发工具“控制台”选项卡中使用这个选项:
console.log(object);
console.log(对象);
#19
5
Assume object obj = {0:'John', 1:'Foo', 2:'Bar'}
假设对象obj = {0:'John', 1:'Foo', 2:'Bar'}
Print object's content
打印对象的内容
for (var i in obj){
console.log(obj[i], i);
}
Console output (Chrome DevTools) :
控制台输出(Chrome DevTools):
John 0
Foo 1
Bar 2
Hope that helps!
希望会有帮助!
#20
4
Javascript Function
Javascript函数
<script type="text/javascript">
function print_r(theObj){
if(theObj.constructor == Array || theObj.constructor == Object){
document.write("<ul>")
for(var p in theObj){
if(theObj[p].constructor == Array || theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
document.write("<ul>")
print_r(theObj[p]);
document.write("</ul>")
} else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
}
}
document.write("</ul>")
}
}
</script>
Printing Object
打印对象
<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script>
通过print_r Javascript
#21
3
A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from Laravel.
在我的项目中,我总是使用一个小的辅助函数来进行简单快速的调试。灵感取自Laravel。
/**
* @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) + ')');
}
Usage
使用
dd(123.55);输出:
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
#22
3
The simplest way:
最简单的方法:
console.log(obj);
Or with a message:
或信息:
console.log("object is: %O", obj);
The first object you pass can contain one or more format specifiers. A format specifier is composed of the percent sign (%) followed by a letter that indicates the formatting to apply.
您传递的第一个对象可以包含一个或多个格式说明符。格式说明符由百分号(%)组成,后面有一个字母表示要应用的格式。
更多的格式说明符
#23
2
i used pagewil's print method, and it worked very nicely.
我使用了pagewil的打印方法,效果非常好。
here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:
这里是我稍微扩展的版本,有(松散的)缩进和不同的支持/ob分隔符:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};
#24
2
Another modification of pagewils code... his doesn't print out anything other than strings and leaves the number and boolean fields blank and I fixed the typo on the second typeof just inside the function as created by megaboss.
pagewils代码的另一个修改…他没有打印任何东西,除了字符串,并留下数字和布尔字段空白,我把typo固定在第二个类型中,就像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;
};
#25
2
probably you are looking for this one
也许你正在找这个。
console.dir()
console.dir()
#26
2
Here's function.
这是函数。
function printObj(obj) {
console.log((function traverse(tab, obj) {
let str = "";
if(typeof obj !== 'object') {
return obj + ',';
}
if(Array.isArray(obj)) {
return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
}
str = str + '{\n';
for(var p in obj) {
str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
}
str = str.slice(0,-2) + str.slice(-1);
str = str + tab + '},';
return str;
}('',obj).slice(0,-1)))};
It can show object using tab indent with readability.
它可以用tab缩进来显示对象的可读性。
#27
1
If you're looking for something that can return a prettified string of any javascript object, check out https://github.com/fresheneesz/beautinator . An example:
如果您正在寻找可以返回任何javascript对象的漂亮字符串的东西,请查看https://github.com/fresheneesz/beautinator。一个例子:
var result = beautinator({ "font-size": "26px","font-family": "'Open Sans', sans-serif",color: "white", overflow: "hidden",padding: "4px 4px 4px 8px",Text: { display: "block", width: "100%","text-align": "center", "padding-left": "2px","word-break": "break-word"}})
console.log(result)
Results in:
结果:
{ "font-size": "26px",
"font-family": "'Open Sans', sans-serif",
color: "white", overflow: "hidden",
padding: "4px 4px 4px 8px",
Text: { display: "block", width: "100%",
"text-align": "center", "padding-left": "2px",
"word-break": "break-word"
}
}
It even works if there are functions in your object.
如果对象中有函数,它甚至会起作用。
#28
-2
It seems that a simple for...in
can't solve the problem especially when we want to tackle apart from custom, host , native or CSSOM objects. Besides, we are talking about debugging here and who knows when and where we'll need it!
似乎很简单……在无法解决问题的情况下,特别是当我们想要处理自定义、主机、本机或c对象时。此外,我们正在讨论调试,谁知道我们何时何地需要它!
My small library can handle objects like this one:
我的小图书馆可以处理像这样的东西:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
and present them colorful and with identation like:
给他们带来丰富多彩的生活,比如:
- 0, foo, 'bar'
- 0,foo,“酒吧”
- 0, loop2, 'contains a circular reference to object at index 0'
- 0,loop2, '包含一个在索引0的对象的循环引用'
- 0, another, 'object'
- 0,另一个“对象”
- 1, a1, 1
- 1,a1,1
- 1, b1, 'baz'
- 1,b1,“记者”
- 1, loop1, 'contains a circular reference to object at index 2'
- 1、loop1,包含一个指向索引2的对象的循环引用
- 1, c1, 'true'
- 1,c1,“真正的”
- 1, d1, ''
- 1,d1。”
- 1, e1, [1,2,3]
- 1、e1(1、2、3)
but see there:
但看到:
- https://github.com/centurianii/jsdebug
- https://github.com/centurianii/jsdebug
- http://jsfiddle.net/centurianii/92Cmk/36/
- http://jsfiddle.net/centurianii/92Cmk/36/
With some precautions even document.body
is parsed!
有一些预防措施甚至文件。身体被解析!
#29
-3
You may use my function .
Call this function with an array or string or an object it alerts the contents.
你可以使用我的功能。用一个数组或字符串或一个对象来调用这个函数,它会通知内容。
Function
函数
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
Usage
使用
var data = [1, 2, 3, 4];
print_r(data);
#1
710
If you want to print the object for debugging purposes, I suggest instead installing Firebug for Firefox and using the code:
如果您想为调试目的打印对象,我建议为Firefox安装Firebug并使用代码:
console.log(obj)
#2
1633
Use native JSON.stringify
method. Works with nested objects and all major browsers support this method.
使用原生JSON。stringify方法。使用嵌套对象和所有主流浏览器都支持这种方法。
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
Link to Mozilla API Reference and other examples.
链接到Mozilla API参考和其他示例。
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
Use a custom JSON.stringify replacer if you encounter this Javascript error
使用自定义JSON。如果遇到这个Javascript错误,stringify replacer。
"Uncaught TypeError: Converting circular structure to JSON"
#3
355
var output = '';
for (var property in object) {
output += property + ': ' + object[property]+'; ';
}
alert(output);
#4
87
console.dir(object)
:
console.dir(对象):
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
显示指定JavaScript对象的属性的交互列表。这个清单允许您使用信息公开三角形来检查子对象的内容。
Note that the console.dir()
feature is non-standard. See MDN Web Docs
注意,console.dir()特性是非标准的。看到MDN Web文档
#5
63
Well, Firefox (thanks to @Bojangles for detailed information) has Object.toSource()
method which prints objects as JSON and function(){}
.
嗯,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和函数(){}。
That's enough for most debugging purposes, I guess.
我想这对于大多数调试来说已经足够了。
#6
63
try this :
console.log(JSON.stringify(obj))
This will print the stringify version of object. So instead of [object]
as an output you will get the content of object.
这将打印对象的stringify版本。因此,您将获得对象的内容,而不是作为输出。
#7
50
If you want to use alert, to print your object, you can do this:
如果你想使用警告,打印你的对象,你可以这样做:
alert("myObject is " + myObject.toSource());
alert(“myObject”+ myObject. tosource ());
It should print each property and its corresponding value in string format.
它应该以字符串格式打印每个属性及其相应的值。
#8
31
Function:
功能:
var print = function(o){
var str='';
for(var p in o){
if(typeof o[p] == 'string'){
str+= p + ': ' + o[p]+'; </br>';
}else{
str+= p + ': { </br>' + print(o[p]) + '}';
}
}
return str;
}
Usage:
用法:
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
Example:
例子:
http://jsfiddle.net/WilsonPage/6eqMn/
http://jsfiddle.net/WilsonPage/6eqMn/
#9
28
In NodeJS you can print an object by using util.inspect(obj). Be sure to state the depth or you'll only have a shallow print of the object. http://nodejs.org/api/util.html#util_util_inspect_object_options
在node . js中,您可以通过使用util. inspection (obj)来打印一个对象。一定要说明深度,否则你只会有一个对象的浅打印。http://nodejs.org/api/util.html util_util_inspect_object_options
#10
26
If you would like to see data in tabular format you can use
如果您希望以表格格式查看数据,您可以使用。
console.table(obj);
Table can be sorted if you click on the table column.
如果单击表列,可以对表进行排序。
You can also select what columns to show:
您还可以选择要显示的列:
console.table(obj, ['firstName', 'lastName']);
You can find more information about console.table here
您可以找到更多关于控制台的信息。表
#11
18
As it was said before best and most simply way i found was
正如我之前所说的,我发现的最简单的方法就是。
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
#12
17
To print the full object with Node.js with colors as a bonus:
用节点打印完整对象。有颜色的js:
console.dir(object, {depth: null, colors: true})
Colors are of course optional, 'depth: null' will print the full object.
颜色当然是可选的,'depth: null'将打印完整的对象。
The options don't seem to be supported in browsers.
这些选项在浏览器中似乎不受支持。
References:
引用:
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://nodejs.org/api/console.html#console_console_dir_obj_options
https://nodejs.org/api/console.html console_console_dir_obj_options
#13
16
Use this:
用这个:
console.log('print object: ' + JSON.stringify(session));
#14
14
If you would like to print the object of its full length, can use
如果你想打印它的全部长度的对象,可以使用。
console.log(require('util').inspect(obj, {showHidden: false, depth: null})
console.log(要求(“跑龙套”)。检查(obj, {showHidden: false, depth: null})
If you want to print the object by converting it to the string then
如果您想要打印对象,请将其转换为字符串。
console.log(JSON.stringify(obj));
console.log(JSON.stringify(obj));
#15
11
I needed a way to recursively print the object, which pagewil's answer provided (Thanks!). I updated it a little bit to include a way to print up to a certain level, and to add spacing so that it is properly indented based on the current level that we are in so that it is more readable.
我需要一种递归打印对象的方法,这是pagewil的答案(谢谢!)我对它进行了一些更新,包括了一种打印到某个级别的方法,并添加了间距,这样它就可以根据当前的级别进行适当缩进,这样就更容易阅读了。
// 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;
};
Usage:
用法:
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) );
#16
9
(This has been added to my library at GitHub)
(这已经被添加到GitHub的我的库中)
Reinventing the wheel here! None of these solutions worked for my situation. So, I quickly doctored up pagewil's answer. This one is not for printing to screen (via console, or textfield or whatever). It is, however, for data transport. This version seems to return a very similar result as toSource()
. I've not tried JSON.stringify
, but I assume this is about the same thing. The result of this function is a valid Javascript object declaration.
重新发明*!这些解决方案都不能解决我的问题。所以,我迅速修改了pagewil的答案。这不是用于打印到屏幕(通过控制台,或textfield或其他什么)。然而,它是用于数据传输的。这个版本似乎返回了与toSource()非常相似的结果。我没有试过JSON。stringify,但是我假设这是一样的。该函数的结果是一个有效的Javascript对象声明。
I wouldn't doubt if something like this was already on SO somewhere, but it was just shorter to make it than to spend a while searching past answers. And since this question was my top hit on google when I started searching about this; I figured putting it here might help others.
我不怀疑这样的事情是否已经发生在某个地方,但它只是比花一段时间搜索过去的答案更短。因为这个问题是我在谷歌上搜索这个问题时的第一反应;我想把它放在这里可能会对其他人有所帮助。
Anyhow, the result from this function will be a string representation of your object, even if your object has embedded objects and arrays, and even if those objects or arrays have even further embedded objects and arrays. (I heard you like to drink? So, I pimped your car with a cooler. And then, I pimped your cooler with a cooler. So, your cooler can drink, while your being cool.)
无论如何,这个函数的结果将是对象的字符串表示,即使对象有嵌入对象和数组,即使这些对象或数组有更深入的嵌入对象和数组。我听说你喜欢喝酒?所以,我给你的车加了个冷气。然后,我用一个冷却器把你的冷却器拉平。所以,你的冷却器可以喝,而你的酷。
Arrays are stored with []
instead of {}
and thus dont have key/value pairs, just values. Like regular arrays. Therefore, they get created like arrays do.
数组被存储为[]而不是{},因此没有键/值对,只有值。像普通数组。因此,它们就像数组一样被创建。
Also, all string (including key names) are quoted, this is not necessary unless those strings have special characters (like a space or a slash). But, I didn't feel like detecting this just to remove some quotes that would otherwise still work fine.
此外,所有字符串(包括键名)都被引用,除非这些字符串有特殊字符(比如空格或斜杠),否则这是不必要的。但是,我不想仅仅是为了删除一些本来还可以正常工作的引号。
This resulting string can then be used with eval
or just dumping it into a var thru string manipulation. Thus, re-creating your object again, from text.
这个结果字符串可以与eval一起使用,或者直接将其转储到一个var thru字符串操作中。因此,从文本重新创建您的对象。
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)+"]";
}
Let me know if I messed it all up, works fine in my testing. Also, the only way I could think of to detect type array
was to check for the presence of length
. Because Javascript really stores arrays as objects, I cant actually check for type array
(there is no such type!). If anyone else knows a better way, I would love to hear it. Because, if your object also has a property named length
then this function will mistakenly treat it as an array.
如果我搞砸了,请告诉我,在我的测试中效果很好。另外,我想要检测类型数组的唯一方法是检查是否存在长度。因为Javascript真的将数组存储为对象,所以实际上我不能检查类型数组(没有这样的类型!)如果有人知道更好的方法,我很乐意听到。因为,如果您的对象也有一个名为length的属性,那么这个函数将错误地将其视为一个数组。
EDIT: Added check for null valued objects. Thanks Brock Adams
编辑:为空值对象添加检查。由于布鲁克亚当斯
EDIT: Below is the fixed function to be able to print infinitely recursive objects. This does not print the same as toSource
from FF because toSource
will print the infinite recursion one time, where as, this function will kill it immediately. This function runs slower than the one above, so I'm adding it here instead of editing the above function, as its only needed if you plan to pass objects that link back to themselves, somewhere.
编辑:下面是能够打印无限递归对象的固定函数。由于toSource将会打印无限递归,所以这个函数将会立即将其杀死。这个函数比上面的函数运行得慢,所以我将它添加到这里,而不是编辑上面的函数,因为它只需要如果您打算将链接返回到它们自己的对象,就需要在某个地方。
const ObjToSource=(o)=> {
if (!o) return null;
let str="",na=0,k,p;
if (typeof(o) == "object") {
if (!ObjToSource.check) ObjToSource.check = new Array();
for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
ObjToSource.check.push(o);
}
k="",na=typeof(o.length)=="undefined"?1:0;
for(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 (typeof(o) == "object") ObjToSource.check.pop();
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
Test:
测试:
var test1 = new Object();
test1.foo = 1;
test1.bar = 2;
var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;
console.log(ObjToSource(testobject));
console.log(testobject.toSource());
Result:
结果:
{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})
NOTE: Trying to print document.body
is a terrible example. For one, FF just prints an empty object string when using toSource
. And when using the function above, FF crashes on SecurityError: The operation is insecure.
. And Chrome will crash on Uncaught RangeError: Maximum call stack size exceeded
. Clearly, document.body
was not meant to be converted to string. Because its either too large, or against security policy to access certain properties. Unless, I messed something up here, do tell!
注意:尝试打印文档。身体就是一个可怕的例子。首先,FF只是在使用toSource时打印一个空的对象字符串。当使用上面的函数时,FF会在SecurityError上崩溃:操作是不安全的。而Chrome将会在未捕获的RangeError上崩溃:超过了最大的调用堆栈大小。显然,文档。身体不应该被转换成字符串。因为它要么太大,要么违反安全策略来访问某些属性。除非,我把事情搞砸了,告诉我!
#17
6
I always use console.log("object will be: ", obj, obj1)
. this way I don't need to do the workaround with stringify with JSON. All the properties of the object will be expanded nicely.
我总是使用控制台。log(“对象将是:”,obj, obj1)。这样我就不需要用JSON来处理stringify。对象的所有属性都将被很好地扩展。
#18
5
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
where object
is your object
对象是什么?
or you can use this in chrome dev tools, "console" tab:
或者你可以在chrome开发工具“控制台”选项卡中使用这个选项:
console.log(object);
console.log(对象);
#19
5
Assume object obj = {0:'John', 1:'Foo', 2:'Bar'}
假设对象obj = {0:'John', 1:'Foo', 2:'Bar'}
Print object's content
打印对象的内容
for (var i in obj){
console.log(obj[i], i);
}
Console output (Chrome DevTools) :
控制台输出(Chrome DevTools):
John 0
Foo 1
Bar 2
Hope that helps!
希望会有帮助!
#20
4
Javascript Function
Javascript函数
<script type="text/javascript">
function print_r(theObj){
if(theObj.constructor == Array || theObj.constructor == Object){
document.write("<ul>")
for(var p in theObj){
if(theObj[p].constructor == Array || theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
document.write("<ul>")
print_r(theObj[p]);
document.write("</ul>")
} else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
}
}
document.write("</ul>")
}
}
</script>
Printing Object
打印对象
<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script>
通过print_r Javascript
#21
3
A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from Laravel.
在我的项目中,我总是使用一个小的辅助函数来进行简单快速的调试。灵感取自Laravel。
/**
* @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) + ')');
}
Usage
使用
dd(123.55);输出:
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
#22
3
The simplest way:
最简单的方法:
console.log(obj);
Or with a message:
或信息:
console.log("object is: %O", obj);
The first object you pass can contain one or more format specifiers. A format specifier is composed of the percent sign (%) followed by a letter that indicates the formatting to apply.
您传递的第一个对象可以包含一个或多个格式说明符。格式说明符由百分号(%)组成,后面有一个字母表示要应用的格式。
更多的格式说明符
#23
2
i used pagewil's print method, and it worked very nicely.
我使用了pagewil的打印方法,效果非常好。
here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:
这里是我稍微扩展的版本,有(松散的)缩进和不同的支持/ob分隔符:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};
#24
2
Another modification of pagewils code... his doesn't print out anything other than strings and leaves the number and boolean fields blank and I fixed the typo on the second typeof just inside the function as created by megaboss.
pagewils代码的另一个修改…他没有打印任何东西,除了字符串,并留下数字和布尔字段空白,我把typo固定在第二个类型中,就像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;
};
#25
2
probably you are looking for this one
也许你正在找这个。
console.dir()
console.dir()
#26
2
Here's function.
这是函数。
function printObj(obj) {
console.log((function traverse(tab, obj) {
let str = "";
if(typeof obj !== 'object') {
return obj + ',';
}
if(Array.isArray(obj)) {
return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
}
str = str + '{\n';
for(var p in obj) {
str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
}
str = str.slice(0,-2) + str.slice(-1);
str = str + tab + '},';
return str;
}('',obj).slice(0,-1)))};
It can show object using tab indent with readability.
它可以用tab缩进来显示对象的可读性。
#27
1
If you're looking for something that can return a prettified string of any javascript object, check out https://github.com/fresheneesz/beautinator . An example:
如果您正在寻找可以返回任何javascript对象的漂亮字符串的东西,请查看https://github.com/fresheneesz/beautinator。一个例子:
var result = beautinator({ "font-size": "26px","font-family": "'Open Sans', sans-serif",color: "white", overflow: "hidden",padding: "4px 4px 4px 8px",Text: { display: "block", width: "100%","text-align": "center", "padding-left": "2px","word-break": "break-word"}})
console.log(result)
Results in:
结果:
{ "font-size": "26px",
"font-family": "'Open Sans', sans-serif",
color: "white", overflow: "hidden",
padding: "4px 4px 4px 8px",
Text: { display: "block", width: "100%",
"text-align": "center", "padding-left": "2px",
"word-break": "break-word"
}
}
It even works if there are functions in your object.
如果对象中有函数,它甚至会起作用。
#28
-2
It seems that a simple for...in
can't solve the problem especially when we want to tackle apart from custom, host , native or CSSOM objects. Besides, we are talking about debugging here and who knows when and where we'll need it!
似乎很简单……在无法解决问题的情况下,特别是当我们想要处理自定义、主机、本机或c对象时。此外,我们正在讨论调试,谁知道我们何时何地需要它!
My small library can handle objects like this one:
我的小图书馆可以处理像这样的东西:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
and present them colorful and with identation like:
给他们带来丰富多彩的生活,比如:
- 0, foo, 'bar'
- 0,foo,“酒吧”
- 0, loop2, 'contains a circular reference to object at index 0'
- 0,loop2, '包含一个在索引0的对象的循环引用'
- 0, another, 'object'
- 0,另一个“对象”
- 1, a1, 1
- 1,a1,1
- 1, b1, 'baz'
- 1,b1,“记者”
- 1, loop1, 'contains a circular reference to object at index 2'
- 1、loop1,包含一个指向索引2的对象的循环引用
- 1, c1, 'true'
- 1,c1,“真正的”
- 1, d1, ''
- 1,d1。”
- 1, e1, [1,2,3]
- 1、e1(1、2、3)
but see there:
但看到:
- https://github.com/centurianii/jsdebug
- https://github.com/centurianii/jsdebug
- http://jsfiddle.net/centurianii/92Cmk/36/
- http://jsfiddle.net/centurianii/92Cmk/36/
With some precautions even document.body
is parsed!
有一些预防措施甚至文件。身体被解析!
#29
-3
You may use my function .
Call this function with an array or string or an object it alerts the contents.
你可以使用我的功能。用一个数组或字符串或一个对象来调用这个函数,它会通知内容。
Function
函数
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
Usage
使用
var data = [1, 2, 3, 4];
print_r(data);