如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
编号:在这些示例中,yourObj定义了要检查的对象。
首先,我最不喜欢但最常用的显示对象的方式:
这是显示对象内容的实际方式
console.log(yourObj)
将产生如下结果:
我认为最好的解决方案是查看对象关键点,然后查看对象值,如果您真的想查看对象的内容。。。
console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));
它将输出如下内容:(上图:存储在对象中的键/值)
如果您使用的是ECMAScript 2016或更高版本,还有一个新选项:
Object.keys(yourObj).forEach(e => console.log(`key=${e} value=${yourObj[e]}`));
这将产生整洁的输出:前面的回答中提到的解决方案:console.log(yourObj)显示了太多的参数,并且不是显示所需数据的最方便用户的方式。这就是为什么我建议分别记录键和值。
下一步:
console.table(yourObj)
有人在之前的评论中建议过这个,但它从来没有对我起过作用。如果它对其他人在不同的浏览器或其他东西上起作用,那就太好了!我仍将代码放在此处以供参考!将向控制台输出如下内容:
其他回答
试试这个:
var object = this.window;
console.log(object,'this is window object');
输出:
这里有一种方法:
console.log("%o", obj);
我需要一种递归打印对象的方法,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;
};
用法:
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) );
使用此项:
console.log('print object: ' + JSON.stringify(session));
最简单的答案
我很惊讶,这没有一个更简单的答案,只是一群人重复着完全相同的2件事,还有一些人用不可读的代码。。。
干得好。如果您只需要将对象作为字符串(无嵌套级别):
function prettyStringifyObject(obj: Record < any, any > ) {
let result = ''
for (const key in obj) {
result = `${result}${result !== '' ? ', ' : ''}${key}: ${Array.isArray(obj[key]) ? `[${obj[key]}]` : obj[key]}`
}
return `{${result}}`
}
测验
使用测试
const someTestObject = {
data: [1, 2, 3, "4"],
aString: "awdasdyhblhyb",
aBoolean: true,
aNumber: 50,
aNull: null
aNestedObject: {
someOtherData: [],
isNested: true
}
}
console.log(prettyStringifyObject(someTestObject))
结果:
"{data: [1,2,3,4], aString: awdasdyhblhyb, aBoolean: true, aNumber: 50, aNull: null, aNestedObject: [object Object]}"
你可以看看我在这里做的JSFiddle