Print content of JavaScript object? [duplicate]

2019-01-01 14:03发布

This question already has an answer here:

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?

15条回答
千与千寻千般痛.
2楼-- · 2019-01-01 14:30

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

查看更多
人间绝色
3楼-- · 2019-01-01 14:30

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);
查看更多
闭嘴吧你
4楼-- · 2019-01-01 14:32

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

查看更多
只若初见
5楼-- · 2019-01-01 14:34

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

查看更多
无与为乐者.
6楼-- · 2019-01-01 14:35

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

查看更多
还给你的自由
7楼-- · 2019-01-01 14:35

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!

查看更多
登录 后发表回答