You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript生成美观表格?解决console.table效果不佳问题

解决console.table生成表格视觉效果不佳的问题

console.table的渲染逻辑是以对象的键作为列名,数组元素按索引对应行,这和你想要的「双列版本列表」布局不匹配,所以会出现索引占一行、版本分散的问题。要实现类似目标图的舒适视觉效果,你可以手动拼接格式化的字符串输出,完全自定义表格结构:

实现代码

export function showNodeVersion(metadata: Metadata[]): void {
    const current = getCurrent(metadata).slice(0, 9).map(m => m.version);
    const lts = getLTS(metadata).slice(0, 9).map(m => m.version);
    
    // 计算列宽:取两个数组中最长版本号的长度,加2作为左右留白
    const columnWidth = Math.max(...current.concat(lts).map(v => v.length)) + 2;
    // 表头和分隔线
    const header = `| ${'Current'.padEnd(columnWidth)} | ${'LTS'.padEnd(columnWidth)} |`;
    const divider = `|${'-'.repeat(columnWidth + 2)}|${'-'.repeat(columnWidth + 2)}|`;
    
    // 拼接每行内容,长度不足的数组补空字符串对齐
    const rows = [];
    const maxRows = Math.max(current.length, lts.length);
    for (let i = 0; i < maxRows; i++) {
        const currVersion = current[i] || '';
        const ltsVersion = lts[i] || '';
        rows.push(`| ${currVersion.padEnd(columnWidth)} | ${ltsVersion.padEnd(columnWidth)} |`);
    }
    
    // 输出完整表格
    console.log(header);
    console.log(divider);
    rows.forEach(row => console.log(row));
}

效果说明

  • 自动适配版本号长度,保证列对齐
  • 用分隔线区分表头和内容,视觉层级清晰
  • 两个版本列表长度不一致时,自动补空对齐,避免布局错乱

如果想要更简洁的无框样式,也可以去掉竖线,只保留空格对齐:

// 简洁版示例
export function showNodeVersion(metadata: Metadata[]): void {
    const current = getCurrent(metadata).slice(0, 9).map(m => m.version);
    const lts = getLTS(metadata).slice(0, 9).map(m => m.version);
    const columnWidth = Math.max(...current.concat(lts).map(v => v.length)) + 4;
    
    console.log(`Current${' '.repeat(columnWidth - 7)}LTS`);
    console.log('-'.repeat(columnWidth * 2));
    const maxRows = Math.max(current.length, lts.length);
    for (let i = 0; i < maxRows; i++) {
        console.log(`${(current[i] || '').padEnd(columnWidth)}${lts[i] || ''}`);
    }
}

内容的提问来源于stack exchange,提问作者CoolPlayLin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:00:31