通常如果我们只使用alert(object);它将显示为[object object]。如何在JavaScript中打印对象的所有内容参数?


当前回答

ie8有开发工具,类似于Firefox的Firebug。Opera有Opera DragonFly,谷歌Chrome也有开发人员工具(Shift+Ctrl+J)。

下面是在IE6-8中调试JavaScript的更详细的答案: 使用IE8“开发人员工具”调试早期IE版本

其他回答

如果你只是想要一个对象的字符串表示,你可以使用JSON。stringify函数,使用JSON库。

使用JSON.stringify,这将为您提供一个缩进的JSON对象的非常好的输出:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

第二个参数(replacer)在返回字符串之前改变字符串的内容。

第三个参数(space)指定使用多少个空格作为可读性空白。

JSON。在这里Stringify文档。

你也可以使用Prototype的object .inspect()方法,该方法“返回对象的面向调试的字符串表示”。

http://api.prototypejs.org/language/Object/inspect/

所有Javascript !

String.prototype.repeat = function(num) {
    if (num < 0) {
        return '';
    } else {
        return new Array(num + 1).join(this);
    }
};

function is_defined(x) {
    return typeof x !== 'undefined';
}

function is_object(x) {
    return Object.prototype.toString.call(x) === "[object Object]";
}

function is_array(x) {
    return Object.prototype.toString.call(x) === "[object Array]";
}

/**
 * Main.
 */
function xlog(v, label) {
    var tab = 0;

    var rt = function() {
        return '    '.repeat(tab);
    };

    // Log Fn
    var lg = function(x) {
        // Limit
        if (tab > 10) return '[...]';
        var r = '';
        if (!is_defined(x)) {
            r = '[VAR: UNDEFINED]';
        } else if (x === '') {
            r = '[VAR: EMPTY STRING]';
        } else if (is_array(x)) {
            r = '[\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + ']';
        } else if (is_object(x)) {
            r = '{\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + '}';
        } else {
            r = x;
        }
        return r;
    };

    // Space
    document.write('\n\n');

    // Log
    document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};



// Demo //

var o = {
    'aaa' : 123,
    'bbb' : 'zzzz',
    'o' : {
        'obj1' : 'val1',
        'obj2' : 'val2',
        'obj3' : [1, 3, 5, 6],
        'obj4' : {
            'a' : 'aaaa',
            'b' : null
        }
    },
    'a' : [ 'asd', 123, false, true ],
    'func' : function() {
        alert('test');
    },
    'fff' : false,
    't' : true,
    'nnn' : null
};

xlog(o, 'Object'); // With label
xlog(o); // Without label

xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');

var no_definido;
xlog(no_definido, 'Undefined!');

xlog(true);

xlog('', 'Empty String');

ie8有开发工具,类似于Firefox的Firebug。Opera有Opera DragonFly,谷歌Chrome也有开发人员工具(Shift+Ctrl+J)。

下面是在IE6-8中调试JavaScript的更详细的答案: 使用IE8“开发人员工具”调试早期IE版本