简体   繁体   English

为什么console.log()和document.write()在JavaScript中为二维数组输出不同的结果?

[英]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. 我试图理解JavaScript中二维数组的来龙去脉。 While debugging I've noticed a difference in the values when outputting with console.log() and document.write(). 在调试时我注意到使用console.log()和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. 我知道我应该使用console.log(),但似乎我只能得到document.write()来输出我期待的内容。

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) : 我从document.write(x)中看到以下内容:

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

I see the following from console.log(x) : 我在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. 登录Firefox会产生与Chrome不同的结果。 Document.write is a Javascript method that has a certain implementation across all browsers, like trim() or any other method. Document.write是一种Javascript方法,在所有浏览器中都有一定的实现,比如trim()或任何其他方法。

Because log() is used for development purposes, it doesn't matter how the data is output, so long as it's useful to developers. 因为log()用于开发目的,所以只要对开发人员有用,数据的输出方式无关紧要。

The answer to this is extremely simple: Chrome minimizes arrays, each of those is an array with two items. 答案非常简单:Chrome最小化阵列,每个阵列都有一个包含两个项目的阵列。 Click on it for it to reveal the content. 单击它以显示内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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