如何显示JavaScript对象?
如何以字符串格式显示JavaScript对象的内容,如当我们如何显示JavaScript对象?,javascript,serialization,javascript-objects,Javascript,Serialization,Javascript Objects,如何以字符串格式显示JavaScript对象的内容,如当我们alert变量时 与我想显示对象的格式相同。好吧,Firefox(感谢@Bojangles提供详细信息)有一个方法,可以将对象打印为JSON和function(){} 我想,对于大多数调试目的来说,这已经足够了。好吧,Firefox(感谢@Bojangles提供了详细信息)有一个方法可以将对象打印为JSON和function(){} 我想,对于大多数调试目的来说,这已经足够了。如果要打印对象进行调试,请使用以下代码: var obj =
alert
变量时
与我想显示对象的格式相同。好吧,Firefox(感谢@Bojangles提供详细信息)有一个方法,可以将对象打印为JSON和function(){}
我想,对于大多数调试目的来说,这已经足够了。好吧,Firefox(感谢@Bojangles提供了详细信息)有一个方法可以将对象打印为JSON和function(){}
我想,对于大多数调试目的来说,这已经足够了。如果要打印对象进行调试,请使用以下代码:
var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)
将显示:
注意:您只能记录对象。例如,这将不起作用:
console.log('My object : ' + obj)
注意“:您也可以在log
方法中使用逗号,然后输出的第一行将是字符串,之后将呈现对象:
console.log('My object: ', obj);
如果要出于调试目的打印对象,请使用以下代码:
var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)
将显示:
注意:您只能记录对象。例如,这将不起作用:
console.log('My object : ' + obj)
注意“:您也可以在log
方法中使用逗号,然后输出的第一行将是字符串,之后将呈现对象:
console.log('My object: ', obj);
如果要使用alert打印对象,可以执行以下操作:
alert(“myObject是”+myObject.toSource())代码>
它应该以字符串格式打印每个属性及其对应的值。如果要使用alert打印对象,可以执行以下操作:
alert(“myObject是”+myObject.toSource())代码>
它应该以字符串格式打印每个属性及其对应的值。使用本机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()
链接到和其他示例
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
如果需要,请使用自定义设置
遇到此Javascript错误
"Uncaught TypeError: Converting circular structure to JSON"
使用本机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()
链接到和其他示例
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
如果需要,请使用自定义设置
遇到此Javascript错误
"Uncaught TypeError: Converting circular structure to JSON"
功能:
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;
}
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
示例:
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;
}
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
功能:
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;
}
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
示例:
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;
}
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
我需要一种递归打印对象的方法,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;
};
我需要一种递归打印对象的方法,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;
};
(这已添加到我的库中,位于)
在这里重新发明轮子!这些解决方案都不适合我的情况。所以,我很快修改了他的答案。这一个不用于打印到屏幕(通过控制台或文本字段或其他方式)。对于警报
,它在这些情况下确实可以正常工作,并且可以按照OP的要求正常工作。这里的许多答案都没有按照OP的要求使用警报
。无论如何,它是为数据传输而格式化的。此版本似乎返回了与toSource()
非常相似的结果。我没有针对JSON.stringify进行测试,但我假设这是相同的。这个版本更像是poly-fil,因此您可以在任何环境中使用它。此函数的结果是一个有效的Javascript对象声明
我不会怀疑这样的事情是否已经在某处上演了,但它只是比花一段时间寻找过去的答案要短。当我开始搜索这个问题时,这个问题是我在谷歌上最热门的问题;我想把它放在这里可能会帮助别人
无论如何,此函数的结果将是对象的字符串表示,即使对象具有嵌入对象和数组,即使这些对象或数组具有进一步的嵌入对象和数组。(我听说你喜欢喝酒?所以,我用冷却器拉你的车。然后,我用冷却器拉你的冷却器。这样,你的冷却器可以在你冷静的时候喝酒。)
数组是用[]
而不是{}
存储的,因此没有键/值对,只有值。就像正则数组一样。因此,它们会像数组一样被创建
此外,所有字符串(包括键名)都被引用,除非这些字符串具有特殊字符(如空格或斜杠),否则这是不必要的。但是,我不想仅仅为了删除一些引用而检测到这一点,否则这些引用仍然可以正常工作
然后,这个结果字符串可以与eval
一起使用,或者通过字符串操作将其转储到var中。因此,从文本重新创建对象
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)+"]";
}
如果我把事情搞砸了,请告诉我,在我的测试中效果很好。此外,我能想到的检测类型数组
的唯一方法是检查长度是否存在。因为Javascript确实将数组存储为对象,所以我实际上无法检查类型array
(没有这样的类型!)。如果有人知道更好的方法,我很想听听。因为,如果对象还有一个名为length
的属性,则此函数将错误地将其视为数组
编辑:添加了空值对象的检查。谢谢布罗克·亚当斯
编辑:下面是能够打印无限递归对象的固定函数。这与FF中的toSource
打印方式不同,因为toSource
将一次性打印无限递归,其中as,此函数将立即终止它。这个函数比上面的函数运行得慢,所以我
console.log(JSON.stringify(obj))
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;
};
for (var i in obj){
console.log(obj[i], i);
}
John 0
Foo 1
Bar 2
/**
* @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) + ')');
}
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
console.dir(object, {depth: null, colors: true})
console.log("%o", obj);
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));
console.log(yourObj)
console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));
Object.keys(yourObj).forEach(e => console.log(`key=${e} value=${yourObj[e]}`));
console.table(yourObj)
JSON.stringify(obj)
var args_string = JSON.stringify(obj);
console.log(args_string);
alert(args_string);
foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};
alert(`${JSON.stringify(obj)}`);
console.log("%o", object);