如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
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;
};
其他回答
我更喜欢使用console.table来获得清晰的对象格式,所以假设您有这个对象:
const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};
您将看到一张整洁易读的表格,如下所示:
它在浏览器中不起作用,您可能只需要在您希望获得对象的有效JS表示而不是JSON的情况下使用它。它只运行节点内联求值
var execSync = require('child_process').execSync
const objectToSource = (obj) =>
execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })
console.log(objectToSource({ a: 1 }))
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
其中object是您的对象
或者您可以在chrome开发工具的“控制台”选项卡中使用此选项:
console.log(对象);
假设对象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
希望这有帮助!
这里有一种方法:
console.log("%o", obj);