简体   繁体   中英

how to print javascript object array?

I would like to mention here I am very new to the JavaScript. I have following JavaScript object array. but how could I print those values in the browser as well? it is not going to print document.write(vehicle);

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

JSON.Stringify would do.

 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.

 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)
})

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