{"title":"请检查以下代码,要求输入新数据总是显示在上一个数据下方drawTable() {\n const { bh, mc, zt, dw, date, arr1, arr2, tableData } = this.data;\n // 清空画布\n let y = this.data.y; // 获取初始值\n const points = [\n { x: 10, y: 10, width: 90, text: '样品编号' },\n { x: 100, y: 10, width: 90, text: '样品名称' },\n { x: 190, y: 10, width: 90, text: '样品状态' },\n { x: 280, y: 10, width: 90, text: '抽样编号' },\n ];\n // 设置字体样式\n this.ctx.clearRect(0, 0, 800, 800);\n this.ctx.setFontSize(14);\n this.ctx.setTextAlign('center');\n this.ctx.setTextBaseline('middle');\n\n for (let i = 0; i < points.length; i++) {\n const point = points[i];\n const text = point.text;\n this.ctx.strokeRect(point.x, point.y, point.width, 30);\n this.ctx.fillText(text, point.x + point.width / 2, point.y + 15);\n };\n\n y = 40\n\n // 添加新内容到 rows 数组\n const newRow = [\n { x: 10, y, width: 90, text: bh },\n { x: 100, y, width: 90, text: mc },\n { x: 190, y, width: 90, text: zt },\n { x: 280, y, width: 90, text: '' }\n ];\n\n this.setData({ rows: [newRow, ...this.data.rows] });\n\n // 绘制 rows 数组中的内容\n for (let i = 0; i < this.data.rows.length; i++) {\n const row = this.data.rows[i];\n for (let j = 0; j < row.length; j++) {\n const point = row[j];\n const text = point.text;\n this.ctx.strokeRect(point.x, point.y, point.width, 30);\n this.ctx.fillText(text, point.x + point.width / 2, point.y + 15);\n row[j].y += 30;\n }\n }\n\n this.ctx.draw();\n}"}代码看起来基本没有错误,只是有一处不太合理的地方。在添加新内容到 rows 数组的时候,应该将新内容插入数组的最前面,而不是最后面。这样才能保证新数据显示在上一个数据的下方。\n\n修改后的代码如下:\n\ndrawTable() {\n const { bh, mc, zt, dw, date, arr1, arr2, tableData } = this.data;\n // 清空画布\n let y = this.data.y; // 获取初始值\n const points = [\n { x: 10, y: 10, width: 90, text: '样品编号' },\n { x: 100, y: 10, width: 90, text: '样品名称' },\n { x: 190, y: 10, width: 90, text: '样品状态' },\n { x: 280, y: 10, width: 90, text: '抽样编号' },\n ];\n // 设置字体样式\n this.ctx.clearRect(0, 0, 800, 800);\n this.ctx.setFontSize(14);\n this.ctx.setTextAlign('center');\n this.ctx.setTextBaseline('middle');\n\n for (let i = 0; i < points.length; i++) {\n const point = points[i];\n const text = point.text;\n this.ctx.strokeRect(point.x, point.y, point.width, 30);\n this.ctx.fillText(text, point.x + point.width / 2, point.y + 15);\n };\n\n y = 40;\n\n // 添加新内容到 rows 数组\n const newRow = [\n { x: 10, y, width: 90, text: bh },\n { x: 100, y, width: 90, text: mc },\n { x: 190, y, width: 90, text: zt },\n { x: 280, y, width: 90, text: '' }\n ];\n\n this.setData({ rows: [newRow, ...this.data.rows] });\n\n // 绘制 rows 数组中的内容\n for (let i = 0; i < this.data.rows.length; i++) {\n const row = this.data.rows[i];\n for (let j = 0; j < row.length; j++) {\n const point = row[j];\n const text = point.text;\n this.ctx.strokeRect(point.x, point.y, point.width, 30);\n this.ctx.fillText(text, point.x + point.width / 2, point.y + 15);\n row[j].y += 30;\n }\n }\n\n this.ctx.draw();\n

JavaScript 代码优化:新增数据显示在上方 - drawTable() 函数改进

原文地址: https://www.cveoy.top/t/topic/pVYD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录