如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?

与显示对象的格式相同。


当前回答

试试看:

console.log(JSON.stringify(obj))

这将打印对象的字符串版本。因此,您将获得object的内容,而不是[object]作为输出。

其他回答

你可以使用我的功能。使用数组或字符串或对象调用此函数,以提醒内容。

作用

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);
    }
}

用法

var data = [1, 2, 3, 4];
print_r(data);

在ES2015中,使用对象文本的速记属性声明语法,您可以记录对象,同时也可以简洁地保留变量名:

console.log("bwib:", bwib, "bwab:", bwab, "bwob": bwob) // old way A
console.log({bwib: bwib, bwab: bwab, bwob: bwob})       // old way B

console.log({bwib, bwab, bwob})                         // ES2015+ way

这里有一种方法:

console.log("%o", obj);

如果要使用alert打印对象,可以执行以下操作:

alert(“myObject是”+myObject.toSource());

它应该以字符串格式打印每个属性及其对应的值。

功能:

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) );

例子:

http://jsfiddle.net/WilsonPage/6eqMn/