用HTML和javas定义书籍对象数组,书籍对象包含:编号、名称、价格等,使用table展示数据
时间: 2024-10-26 20:16:17 浏览: 64
在HTML和JavaScript中,你可以创建一个书籍对象数组来表示一组书籍,每个书籍对象包含属性如编号(id)、名称(name)和价格(price)。首先,定义书籍对象:
```javascript
// 定义书籍对象构造函数
function Book(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
// 创建书籍对象数组
let bookArray = [
new Book(1, '书名1', 20),
new Book(2, '书名2', 30),
new Book(3, '书名3', 40)
];
```
接下来,你可以使用JavaScript将这个数组转换成HTML表格,显示在页面上:
```javascript
// 将书籍数组转化为HTML table
function createTableFromBooks(books) {
let tableHtml = '<table border="1">';
// 添加表头
tableHtml += '<tr><th>编号</th><th>名称</th><th>价格</th></tr>';
books.forEach(book => {
tableHtml += '<tr>';
tableHtml += `<td>${book.id}</td>`;
tableHtml += `<td>${book.name}</td>`;
tableHtml += `<td>${book.price}</td>`;
tableHtml += '</tr>';
});
tableHtml += '</table>';
return tableHtml;
}
// 渲染到页面上
document.getElementById('bookTable').innerHTML = createTableFromBooks(bookArray);
```
在这个例子中,我们假设有一个HTML元素`<div id="bookTable"></div>`用于显示表格。当你运行这段代码,它会在指定的位置生成一个表格,展示每本书的信息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)