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

与显示对象的格式相同。


当前回答

试试这个:

var object = this.window;
console.log(object,'this is window object');

输出:

其他回答

试试这个:

var object = this.window;
console.log(object,'this is window 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);

显示对象内容的一种简单方法是使用console.log,如下所示

console.log("Object contents are ", obj);

请注意,我没有使用“+”连接对象。如果我使用“+”,那么我将只得到If对象的字符串表示,类似于[Objectobject]。

我在项目中总是使用一个小助手函数,通过控制台进行简单、快速的调试。灵感来自拉雅维尔。

/**
 * @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) + ')');
}

用法

日(123.55);输出:

var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj'); 

console.dir(对象):

显示指定JavaScript对象的财产的交互式列表。此列表允许您使用公开三角形来检查子对象的内容。

请注意,console.dir()特性是非标准的。查看MDN Web文档