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

将对象作为参数传递时如何获取其名称?使用模板字面量未成功

问题解决方案

根本原因

直接把普通对象放入模板字面量时,JS会自动调用对象的默认toString()方法,原生JS普通对象的该方法返回值固定为[object Object],因此无法得到预期输出。

不同场景实现方案

场景1:需要输出对象的实际内容

这是最常见的需求,有两种常用实现方式:

  • 用JSON.stringify()序列化对象后输出:
const theObject = {
    prop1: "sth",
    prop2: "sthesee"
}
function theFun(theArg) {
    // 如需格式化缩进可以加后两个参数:JSON.stringify(theArg, null, 2)
    console.log(`${JSON.stringify(theArg)}`);
}
theFun(theObject);
  • 给对象自定义toString()方法,适配模板字面量的自动转换逻辑:
const theObject = {
    prop1: "sth",
    prop2: "sthesee",
    toString() {
        // 自定义输出格式即可
        return `{ prop1: ${this.prop1}, prop2: ${this.prop2} }`;
    }
}
function theFun(theArg) {
    console.log(`${theArg}`); // 自动调用自定义toString方法输出预期内容
}
theFun(theObject);

场景2:需要获取对象对应的变量名字符串theObject

JS运行时默认不会存储值对应的变量名,因此需要手动绑定标识,两种实现方案:

  • 给对象添加name属性存储标识:
const theObject = {
    name: "theObject",
    prop1: "sth",
    prop2: "sthesee"
}
function theFun(theArg) {
    console.log(`${theArg.name}`); // 输出 theObject
}
theFun(theObject);
  • 传参时用对象解构包装,直接提取键名:
const theObject = {
    prop1: "sth",
    prop2: "sthesee"
}
function theFun(wrappedArg) {
    const objName = Object.keys(wrappedArg)[0];
    console.log(objName); // 输出 theObject
    const originalObj = wrappedArg[objName]; // 可同时拿到原对象内容
}
// 传参时用{ 变量名 }的结构包装
theFun({ theObject });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:09