我上课的第三天,我们应该开车观察物品。我有四个对象。我想为每个人制作一张桌子,左边是他们的钥匙,右边是他们的值。四张桌子并排。我宁愿循环通过按键来完成和循环键盘,因为我一直在玩,并且惨遭失败。任何帮助将不胜感激。我有四个div并排,我想填表。这是我的对象:
以下是我的对象和值:
let Accord = new Car("Accord", 22500, "Crystal White", "alloy", "bose", "leather", "tinted");
let CRV= new Car("CR-V", 28400, "Midnight Black", "alloy", "stock", "cloth", "no tint");
let Pilot = new Car("Pilot", 36796, "Modern Gray Metallic", "alloy", "bose", "leather", "tinted");
let Fit = new Car("Fit", 17499, "Raspberry Blue", "steel", "stock", "cloth", "no tint");
//Here is the entire object:
class Car extends Vehicle {
wheels: string;
stereo: string;
seatsMaterial: string;
tint: string;
constructor(model, price, color, wheels, stereo, seatsMaterial, tint) {
super(model, price, color);
this.wheels = wheels;
this.stereo = stereo;
this.seatsMaterial = seatsMaterial;
this.tint = tint;
}
}
答案 0 :(得分:3)
基本上,您希望迭代数组中的项目并为每个项目绘制一个新行。
可以这样轻松地完成:
function makeTable ( object ) {
// Check type
if ( typeof object !== 'object' ) return false;
// Start our HTML
var html = "<table><tbody>";
// Loop through members of the object
for ( var key in object ) {
// https://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
if ( !object.hasOwnProperty(key) ) continue;
// Add our row:
html += "<tr><th>" + key + "</th><td>" + object[key] + "</td></tr>";
}
// Finish the table:
html += "</tbody></table>";
// Return the table
return html;
}
然后你可以像这样运行它:
document.body.innerHTML = makeTable(myCarObject);
document.getElementById('some-id').innerHTML = makeTable(myCarObject);
有关上述代码的一些说明
.hasOwnProperty
调用 - 正如here所述,有时对象在循环时可能会有意外的属性。这是由于他们的原型以及他们从中继承的任何属性。确保代码按预期运行的一种好方法是在对象没有此属性时continue
循环