如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
我更喜欢使用console.table来获得清晰的对象格式,所以假设您有这个对象:
const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};
您将看到一张整洁易读的表格,如下所示:
其他回答
看起来很简单。。。in无法解决这个问题,特别是当我们想要处理自定义、主机、本机或CSCOM对象之外的问题时。此外,我们正在讨论调试,谁知道我们何时何地需要它!
我的小型库可以处理以下对象:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
并呈现出丰富多彩的标识,如:
0,foo,'bar'0,loop2,'包含对索引0'0处的对象的循环引用,另一个,'object'1,a1,11,b1,'baz'1,loop1,'包含索引2'1,c1,'true'1,d1,''1,e1,[1,2]处的对象循环引用
但请看这里:
https://github.com/centurianii/jsdebughttp://jsfiddle.net/centurianii/92Cmk/36/
通过一些预防措施,甚至可以解析document.body!
console.log()在调试对象方面做得很好,但如果您希望将对象打印到页面内容中,这里是我提出的模仿PHP print_r()功能的最简单方法。很多其他答案都想重新发明轮子,但在JavaScript的JSON.stringify()和HTML的<pre>标记之间,你可以得到你想要的东西。
var obj={name:'名称',联系人:{email:'thename@gmail.com',电话:'123456789'};$('body').append('<pre>'+JSON.stringify(obj,null,4)+'</pre>');<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script>
我需要一种递归打印对象的方法,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) );
最简单的答案
我很惊讶,这没有一个更简单的答案,只是一群人重复着完全相同的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
假设对象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
希望这有帮助!