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

JavaScript对象调用函数打印时出现Undefined问题求助

问题原因与解决方法

为什么会出现undefined?

JavaScript中,函数如果没有显式使用return语句返回值,默认会返回undefined。

看你的代码:

let user = {
    firstname:'faiz',
    lastname:'mohammed',
    fun : function()  {
        let full_name = (this.firstname + " " + this.lastname);
        console.log(full_name); // 这里仅打印内容,但没有返回值
        },
}

console.log(user.fun());

执行时会分两步:

  1. 调用user.fun(),函数内部执行console.log(full_name),输出faiz mohammed;
  2. 因为fun()没有返回值,默认返回undefined,所以外层的console.log()会把这个undefined也打印出来。

而直接拼接的代码console.log(user.firstname + " " + user.lastname)是直接把拼接好的字符串传给console.log,没有函数返回值的问题,所以只会输出一次名字。

两种解决办法

方法1:让函数返回结果,外层打印返回值

修改fun函数,添加return语句返回拼接好的名字,这样外层console.log就会打印函数返回的字符串,而非undefined:

let user = {
    firstname:'faiz',
    lastname:'mohammed',
    fun : function()  {
        let full_name = this.firstname + " " + this.lastname;
        return full_name; // 返回拼接结果
        },
}

console.log(user.fun()); // 打印函数返回的字符串

执行输出:

faiz mohammed

方法2:直接调用函数,不用外层套console.log

如果函数内部已经负责打印,直接调用函数即可,不需要再用console.log包裹:

let user = {
    firstname:'faiz',
    lastname:'mohammed',
    fun : function()  {
        let full_name = this.firstname + " " + this.lastname;
        console.log(full_name);
        },
}

user.fun(); // 直接调用,内部已完成打印

执行输出:

faiz mohammed

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:51:19