为什么JS控制台返回一个额外的未定义? [英] Why does the JS console return an extra undefined?

查看:115
本文介绍了为什么JS控制台返回一个额外的未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我这里发生了什么(在Firefox和Chrome中测试)。

Can someone tell me what's going on here (tested in Firefox and Chrome).

我有一个简单的函数返回一个闭包。

I have a simple function returning a closure.

function say (name) {
  var msg = 'hallo';
  return function () {
    console.log(msg, name);
  }
}

var sayName = say('joe');
sayName();

如果检查浏览器控制台,我会得到预期的结果:

If check the browser console I get the expected result:

Hallo Joe

最后一行,并从控制台运行sayName()我得到以下:

However, if I leave out the last line and run sayName() from the console I get the following:

Hallo Joe
undefined

额外的未定义来自哪里?

Where is the extra undefined coming from?

推荐答案

控制台输出你正在执行的函数的返回值。

The console outputs the return value of the function you're executing.

看看如果你在你的函数例如

See what happens if you put a return statement in your function e.g.

return function () {
    console.log(msg, name);
    return "If you run me from console you'll see this line";
}

这篇关于为什么JS控制台返回一个额外的未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆