简体   繁体   中英

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";

document.write(x);
console.log(x);

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

A,Apple,B,Banana,C,Cumquats,D,Dewberry,E,Elderberry

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

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

By my understanding, console is different based on the vendor of the browser. Logging in Firefox gives a different result than with Chrome. Document.write is a Javascript method that has a certain implementation across all browsers, like trim() or any other method.

Because log() is used for development purposes, it doesn't matter how the data is output, so long as it's useful to developers.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM