如何基于5个对象构建数据集并绘表格?如何用document.write输出产品属性?
嘿,我来帮你搞定这个问题!你已经有了现成的产品数据集,接下来咱们一步步实现你要的两个功能:用document.write输出所有产品属性,以及把这些数据做成清晰的表格。
首先先把你代码里没写完的最后一个产品价格补全(不然会有语法错误),完整的数据集是这样的:
var products = [ { name: 'Samsung Galaxy S8 64GB', count: 2, prise: 21999 }, { name: 'Huawei P20 Lite 4/64GB Klein Blue', count: 0, prise: 11999 }, { name: 'Lenovo K6 (K33a8) Grey', count: 0, prise: 3222 }, { name: 'Xiaomi Redmi Note 4 3/32GB Snapdargon Black (Международная версия)', count: 4, prise: 4399 }, { name: 'Samsung Galaxy A8 2018 32GB Black', count: 0, prise: 13999 } ];
1. 使用
document.write输出所有产品及其属性 你可以通过遍历数组里的每个产品对象,把每个属性拼接成HTML内容后输出。这里用forEach遍历会很方便,代码如下:
// 遍历每个产品,输出属性 products.forEach(function(product) { // 用模板字符串拼接内容,排版更清晰 document.write(` <div style="margin: 10px 0; padding: 10px; border: 1px solid #eee;"> <strong>产品名称:</strong> ${product.name}<br> <strong>库存数量:</strong> ${product.count}<br> <strong>价格:</strong> ${product.prise} </div> `); });
这段代码会给每个产品生成一个带边框的区块,把名称、库存、价格都展示出来。如果你觉得样式没必要,也可以简化成用<p>标签包裹内容。
2. 将产品数据绘制为HTML表格
要把数据做成表格,我们可以直接用document.write拼接完整的表格HTML,或者用DOM元素创建的方式(更推荐后者,不会覆盖页面内容)。
方法一:直接用document.write拼接表格
这种方式简单直接,适合页面加载初期使用:
// 输出表格 document.write(` <table border="1" cellpadding="8" cellspacing="0" style="border-collapse: collapse;"> <thead> <tr style="background-color: #f5f5f5;"> <th>产品名称</th> <th>库存数量</th> <th>价格</th> </tr> </thead> <tbody> `); // 遍历产品生成表格行 products.forEach(function(product) { document.write(` <tr> <td>${product.name}</td> <td>${product.count}</td> <td>${product.prise}</td> </tr> `); }); // 闭合表格标签 document.write('</tbody></table>');
这里给表格加了一些基础样式,比如边框合并、表头背景色,让表格看起来更舒服。
方法二:创建DOM元素添加到页面(更推荐)
如果是在页面加载完成后动态添加表格,用这种方式不会覆盖整个页面内容,灵活性更高:
// 创建表格元素 var table = document.createElement('table'); table.style.borderCollapse = 'collapse'; table.setAttribute('border', '1'); table.setAttribute('cellpadding', '8'); // 创建表头 var headerRow = document.createElement('tr'); headerRow.style.backgroundColor = '#f5f5f5'; // 表头文本数组 var headers = ['产品名称', '库存数量', '价格']; headers.forEach(function(headerText) { var th = document.createElement('th'); th.textContent = headerText; headerRow.appendChild(th); }); table.appendChild(headerRow); // 填充表体数据 products.forEach(function(product) { var row = document.createElement('tr'); // 创建名称单元格 var nameCell = document.createElement('td'); nameCell.textContent = product.name; row.appendChild(nameCell); // 创建库存单元格 var countCell = document.createElement('td'); countCell.textContent = product.count; row.appendChild(countCell); // 创建价格单元格 var priceCell = document.createElement('td'); priceCell.textContent = product.prise; row.appendChild(priceCell); table.appendChild(row); }); // 把表格添加到页面的body中(或者你指定的容器) document.body.appendChild(table);
最后提醒一下:你的代码里价格字段拼写成了prise,如果是笔误可以改成price,不过只要保持一致就没问题~
内容的提问来源于stack exchange,提问作者Alexeii Kozachuk
相关产品推荐
相关产品推荐

