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

如何将console.log输出内容转为字符串并保留原生输出格式

解决方案

Node.js 环境

直接使用Node.js内置的util.format方法即可,它是console.log底层用来做参数格式化的原生API,输出结果和console.log完全一致,天然支持循环引用、深度嵌套对象、多参数、所有JS内置类型的格式化。
示例代码:

const util = require('util');

const a = {};
a.b = a;

// 单参数校验
console.log(util.format(a) === '<ref *1> { b: [Circular *1] }'); // 输出 true

// 多参数场景,和console.log行为完全对齐
console.log(util.format('用户名: %s, 年龄: %d, 扩展信息: %o', '李四', 20, a));

浏览器/跨环境通用实现

如果需要在浏览器端或者做跨环境兼容,可以手动实现对齐console.log输出规则的stringify函数,核心逻辑是维护已访问对象的映射处理循环引用,同时匹配不同JS类型的原生输出格式,支持多参数拼接。
参考实现:

function stringify(...args) {
  const visited = new Map();
  const refMap = new Map();
  let refCount = 1;

  // 第一轮遍历标记所有重复引用的对象
  function markRefs(val) {
    if (typeof val !== 'object' || val === null) return;
    if (visited.has(val)) {
      if (!refMap.has(val)) {
        refMap.set(val, refCount++);
      }
      return;
    }
    visited.set(val, true);
    if (Array.isArray(val)) {
      val.forEach(item => markRefs(item));
    } else {
      Object.values(val).forEach(v => markRefs(v));
    }
  }

  // 第二轮遍历格式化值
  function formatValue(val) {
    if (val === null) return 'null';
    if (val === undefined) return 'undefined';
    const type = typeof val;
    if (type === 'string') return `'${val}'`;
    if (['number', 'boolean', 'symbol', 'function'].includes(type)) {
      return String(val);
    }
    if (val instanceof Date) return val.toString();
    if (val instanceof RegExp) return val.toString();

    // 处理循环引用
    if (refMap.has(val)) {
      return `[Circular *${refMap.get(val)}]`;
    }

    const refPrefix = refMap.has(val) ? `<ref *${refMap.get(val)}> ` : '';
    // 处理数组
    if (Array.isArray(val)) {
      const items = val.map(item => formatValue(item)).join(', ');
      return `${refPrefix}[${items}]`;
    }
    // 处理普通对象
    const entries = Object.entries(val).map(([k, v]) => `${k}: ${formatValue(v)}`).join(', ');
    return `${refPrefix}{ ${entries} }`;
  }

  args.forEach(arg => markRefs(arg));
  return args.map(arg => formatValue(arg)).join(' ');
}

// 测试用例
const a = {};
a.b = a;
console.log(stringify(a) === '<ref *1> { b: [Circular *1] }'); // 输出 true
// 多参数测试
console.log(stringify('测试输出', 123, undefined, a));

你可以根据实际需求扩展对Map、Set、ArrayBuffer等特殊内置对象的格式化逻辑,即可完全对齐console.log的输出效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:21:02