简体   繁体   中英

How to display multi dimensional Javascript array in tabular format in the console?

I have searched everywhere, I didn't notice this weird interaction at first but now I am, I am learning JavaScript in codeacademy and i'm stuck in Arrays and Objects in JavaScript, when I do this:

var newArray = [[1, 1, 1], [1, 1, 1], [1, 1, 1]];
console.log(newArray)

It logs the code as in the same line instead of having 3 rows and 3 columns as it is asked by the exercise, however it lets me pass it, I have searched on their forums and there's users asking for the same thing unanswered, I've tried the possible fixes like resetting the browser and even changing browser.

Try console.table() .

var newArray = [[1, 1, 1], [1, 1, 1], [1, 1, 1]];
console.table(newArray);

Here is a good list of all the console commands available for future reference: https://developer.mozilla.org/en/docs/Web/API/console

This is what it will look like in Firefox (will look similar in other browsers).

在此处输入图片说明

Try console.table(newArray) instead, if you're using Chrome.

Otherwise console.dir(newArray) might make things a bit better.

You could also use a custom logger:

var newArray = [[1,1,1], [1,1,1], [1,1,1]];

var logArrayOfArrays = function(array){
   var length = array.length;
   for(var i = 0; i < length ; i++){
       console.log(array[i]);
  }
}

logArrayOfArrays(newArray);

That's normal, and might even be different from browser to browser, as there's no specification as to how console.log output should be formatted.

You can write:

var newArray = [[1, 1, 1], [1, 1, 1], [1, 1, 1]];
console.log(newArray[0]);
console.log(newArray[1]);
console.log(newArray[2]);
console.log(newArray[3]);

This will output the individual "subarrays" on separate lines.

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