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

为何JavaScript中arryIncludesAlt函数输出undefined?求解析

问题解答:函数返回值与undefined输出原因

两个函数的核心差异

arryIncludesMain

这个函数通过 return 语句明确返回 arr.includes(item) 的布尔结果(true/false)。当你用 console.log 调用它时,其实是在打印函数返回的这个布尔值,所以输出就是纯粹的 true 或 false,不会有额外内容。

arryIncludesAlt

这个函数没有写 return 语句。它内部直接用 console.log 输出 "true" 或 "false",但函数本身没有返回任何值。在 JavaScript 里,只要函数没有显式返回内容,就会默认返回 undefined。

为什么会出现 undefined?

当你执行 console.log(arryIncludesAlt(myArray, 3)) 时,流程是这样的:

  1. 先运行 arryIncludesAlt 函数,它内部打印出 "true";
  2. 接着,console.log 要打印这个函数的返回值,但因为函数没返回东西,所以只能打印默认的 undefined。

同理,调用 arryIncludesAlt(myArray,6) 时,先打印 "false",再打印 undefined,这就是你看到输出里成对出现的原因。

总结

  • arryIncludesMain:把判断结果返回给外部,由外部(比如 console.log)处理输出;
  • arryIncludesAlt:自己内部完成输出,但函数本身无返回值,导致外部 console.log 输出了默认的 undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:12:51