[英]How to add column names to 2d array when printing with console.table() javascript
If I have a 2d array like this...如果我有这样的二维数组......
var x = [
[0, 1, 2],
[0, 1, 2],
[0, 1, 2]
]
And I want to print it to the console using console.table()
but I also want to add column names, how do I do that?我想使用console.table()
将它打印到控制台,但我也想添加列名,我该怎么做?
I see in the documentation its really easy when its an array of objects, but when I try to add column names to this 2d array it messes with the array dimensions and does not print correctly.我在文档中看到,当它是一个对象数组时,它真的很容易,但是当我尝试将列名添加到这个二维数组时,它会混淆数组维度并且无法正确打印。
EDIT: All of the answers this far have said what I said I already knew, that this was easy to do with an array of objects.编辑:到目前为止,所有答案都说明了我所说的我已经知道的,这很容易用一组对象来完成。 My question is, "Is it possible to add column names if you are passing a 2d array."我的问题是,“如果您传递二维数组,是否可以添加列名。”
You need to pass an array of objects to console.table()
in order for it to display with column names, exammple below using your data:您需要将对象数组传递给console.table()
以便它显示列名,例如下面使用您的数据:
const arrayOfObjects = new Array(10).fill({
columnOne : 0,
columnTwo: 1,
columnThree: 2
})
console.table(arrayOfObjects)
Here is a screenshot directly from the Developer Tools Console in Chrome.这是直接来自 Chrome 中的开发者工具控制台的屏幕截图。
More info can be found here regarding this function: https://developer.mozilla.org/en-US/docs/Web/API/Console/table可以在此处找到有关此 function 的更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Console/table
If the array contains objects, then the columns are labeled with the property name.如果数组包含对象,则使用属性名称标记列。 So you can convert the elements to objects with relevant names as properties.因此,您可以将元素转换为具有相关名称作为属性的对象。
var x = [
[0, 1, 2],
[0, 1, 2],
[0, 1, 2]
]
function ARR(first, second, third) {
this.first = first;
this.second = second;
this.third = third;
}
let itemArr = x.map( item => new ARR(...item))
console.table(itemArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.