如何在 JavaScript 中打印对象数组?

问题描述:

我在 JavaScript 中创建了一个对象数组.如何在浏览器窗口中打印对象数组,类似于 PHP 中的 print_r 函数?

I have created an object array in JavaScript. How can I print the object array in the browser window, similar to print_r function in PHP?

var lineChartData = [{
            date: new Date(2009, 10, 2),
            value: 5
        }, {
            date: new Date(2009, 10, 25),
            value: 30
        }, {
            date: new Date(2009, 10, 26),
            value: 72,
            customBullet: "images/redstar.png"
        }];

Simply stringify 您的对象并将其分配给 innerHTML.

yourContainer.innerHTML = JSON.stringify(lineChartData);

如果你想要更漂亮的东西,那就去做

If you want something prettier, do

yourContainer.innerHTML = JSON.stringify(lineChartData, null, 4);

var lineChartData = [{
            date: new Date(2009, 10, 2),
            value: 5
        }, {
            date: new Date(2009, 10, 25),
            value: 30
        }, {
            date: new Date(2009, 10, 26),
            value: 72,
            customBullet: "images/redstar.png"
        }];

document.getElementById("whereToPrint").innerHTML = JSON.stringify(lineChartData, null, 4);

<pre id="whereToPrint"></pre>

但如果你只是为了调试而这样做,那么你最好使用带有 console.log(lineChartData) 的控制台.

But if you just do this in order to debug, then you'd better use the console with console.log(lineChartData).