简体   繁体   English

如何打印javascript对象数组?

[英]how to print javascript object array?

I would like to mention here I am very new to the JavaScript.我想在这里提一下,我对 JavaScript 非常陌生。 I have following JavaScript object array.我有以下 JavaScript 对象数组。 but how could I print those values in the browser as well?但是我怎么能在浏览器中打印这些值呢? it is not going to print document.write(vehicle);它不会打印document.write(vehicle);

 var vehicle = [{name:'Van',wheel:4,chasino:0005}, {name:'Bus',wheel:6,chasino:0006}]; document.write(vehicle);

JSON.Stringify would do. JSON.Stringify可以。

 var vehicle = [{name:'Van',wheel:4,chasino:0005}, {name:'Bus',wheel:6,chasino:0006}]; document.write(JSON.stringify(vehicle));

To print just the values -只打印值 -

 var vehicle = [{name:'Van',wheel:4,chasino:0005}, {name:'Bus',wheel:6,chasino:0006}]; document.write( vehicle .map(v => Object.values(v)) // retrive values from objects .flat() // make linear array .join("<br/>") // for new line as separator );

not sure I understood what you wanted your code to do, but in order to print the contents of your objects in 'vehicle' array, I would suggest this:不确定我是否理解您希望代码执行的操作,但是为了在“车辆”数组中打印对象的内容,我建议这样做:

 const body = document.querySelector("body"); var vehicle = [ { name: "Van", wheel: 4, chasino: 0005 }, { name: "Bus", wheel: 6, chasino: 0006 } ]; const container = document.createElement("div"); for (const objIndex of vehicle) { const list = document.createElement("ul"); list.setAttribute("class", objIndex); for (const key in objIndex) { const liElement = document.createElement("li"); liElement.innerHTML = `${key}:${objIndex[key]}`; list.appendChild(liElement); } container.appendChild(list); } body.appendChild(container);

 Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) {s = "0" + s;} return s; } var vehicle = [{name:'Van',wheel:4,chasino:0005}, {name:'Bus',wheel:6,chasino:0006}]; for(i=0;i<vehicle.length;i++){ document.write(vehicle[i].name+" "+vehicle[i].wheel+" "+vehicle[i].chasino.pad(3)+" "); }

 var vehicle = [{name:'Van',wheel:4,chasino:0005}, {name:'Bus',wheel:6,chasino:0006}]; document.write( vehicle.map(a => Object.values(a).join(' ')) .join('<br>') );

You would want to use the string '0005' instead of number to preserve the '000' characters.您可能希望使用字符串'0005'而不是数字来保留'000'字符。

 var vehicle = [{name:'Van',wheel:4,chasino:'0005'}, {name:'Bus',wheel:6,chasino:'0006'}]; document.write( vehicle.map(a => Object.values(a).join(' ')) .join('<br>') );

Try this...尝试这个...

vehicle.map(v => {
    document.write(v.name)
    document.write(v.wheel)
    document.write(v.chasino)
})

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

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