Print content of JavaScript object? [duplicate]

2019-01-01 14:29发布

问题:

This question already has an answer here:

  • How can I display a JavaScript object? 35 answers

Typically if we just use alert(object); it will show as [object Object]. How to print all the content parameters of an object in JavaScript?

回答1:

If you are using Firefox, alert(object.toSource()) should suffice for simple debugging purposes.



回答2:

This will give you very nice output with indented JSON object:

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

The second argument alters the contents of the string before returning it. The third argument specifies how many spaces to use as white space for readability.



回答3:

Aside from using a debugger, you can also access all elements of an object using a foreach loop. The following printObject function should alert() your object showing all properties and respective values.

function printObject(o) {
  var out = \'\';
  for (var p in o) {
    out += p + \': \' + o[p] + \'\\n\';
  }
  alert(out);
}

// now test it:
var myObject = {\'something\': 1, \'other thing\': 2};
printObject(myObject);

Using a DOM inspection tool is preferable because it allows you to dig under the properties that are objects themselves. Firefox has FireBug but all other major browsers (IE, Chrome, Safari) also have debugging tools built-in that you should check.



回答4:

If you just want to have a string representation of an object, you could use the JSON.stringify function, using a JSON library.



回答5:

Print content of object you can use

console.log(obj_str);

you can see the result in console like below.

Object {description: \"test\"} 

For open console press F12 in chrome browser, you will found console tab in debug mode.



回答6:

You could Node\'s util.inspect(object) to print out object\'s structure.

It is especially helpful when your object has circular dependencies e.g.

$ node

var obj = {
   \"name\" : \"John\",
   \"surname\" : \"Doe\"
}
obj.self_ref = obj;

util = require(\"util\");

var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: \'John\', surname: \'Doe\', self_ref: [Circular] }

It that case JSON.stringify throws exception: TypeError: Converting circular structure to JSON



回答7:

You should consider using FireBug for JavaScript debugging. It will let you interactively inspect all of your variables, and even step through functions.



回答8:

Use dir(object). Or you can always download Firebug for Firefox (really helpful).



回答9:

Javascript for all!

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


回答10:

You can give your objects their own toString methods in their prototypes.



回答11:

You can use json.js from http://www.json.org/js.html to change json data to string data.



回答12:

You can also use Prototype\'s Object.inspect() method, which \"Returns the debug-oriented string representation of the object\".

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



回答13:

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

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

Usage

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


回答14:

Internet Explorer 8 has developer tools which is similar to Firebug for Firefox. Opera has Opera DragonFly, and Google Chrome also has something called Developer Tools (Shift+Ctrl+J).

Here is more a more detailed answer to debug JavaScript in IE6-8: Using the IE8 'Developer Tools' to debug earlier IE versions



回答15:

I faced similar problem, The reason for it was i make use of ajax to fetch data. In this case i had made two asynchronous ajax call. In one i just return string msg and show in alert. In second ajax call i fetch arraylist in json format and decode it in js. So my second request use to process first and i was getting alert of object.

So just check. 1. alert should contain string. 2. If u get arrayList or any other Object decode it.

All the best!