fakeguybrushthreepwood fakeguybrushthreepwood - 3 years ago 209
Javascript Question

Why does console.log() and document.write() output different results for a two-dimensional array in JavaScript?

I'm trying to understand the ins and outs of a two-dimensional arrays in JavaScript. While debugging I've noticed a difference in the values when outputting with console.log() and document.write().

I understand I should be using console.log(), however it seems I could only get document.write() to output what I was expecting.

var x = [];
for (var i = 0; i < 5; i++) {
x[i] = new Array(1);
x[0][0] = "A";
x[0][1] = "Apple";
x[1][0] = "B";
x[1][1] = "Banana";
x[2][0] = "C";
x[2][1] = "Cumquats";
x[3][0] = "D";
x[3][1] = "Dewberry";
x[4][0] = "E";
x[4][1] = "Elderberry";


I see the following from document.write(x):


I see the following from console.log(x):

[Array[2], Array[2], Array[2], Array[2], Array[2]]

Answer Source

The answer to this is extremely simple: Chrome minimizes arrays, each of those is an array with two items. Click on it for it to reveal the content.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download