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

为什么JavaScript函数执行完成后会返回undefined?

为什么你的函数调用会输出undefined

你的randomNum函数里只有console.log语句,没有用return关键字返回任何值。在JavaScript里,只要函数没有明确写return语句,执行结束后就会默认返回undefined。

你写的console.log(randomNum(5))会分两步执行:

  1. 先运行randomNum(5),函数内部打印ok;
  2. 因为函数没返回值,所以randomNum(5)的结果是undefined,外层的console.log就把这个结果也打印出来了。

如果不想看到多余的undefined,可以这么改:

  • 直接调用函数,不用外层的console.log:
    randomNum(5); // 只会输出'ok',不会出现undefined
    
  • 给函数加return语句,让它返回指定内容(可选):
    function randomNum(n) {
      const numbers = [1,2,3,4,5,6,7,8,9,10]
      if(numbers.includes(n)) {
        console.log('ok');
        return 'ok';
      } else {
        console.log('Choose a value between 1 and 10');
        return 'Choose a value between 1 and 10';
      }
    }
    console.log(randomNum(5)); // 先打印'ok',再打印返回的'ok'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:00:46