简体   繁体   English

如何摆脱JavaScript中的“未定义”?

[英]How to get rid of this “undefined” in javascript?

I have following JavaScript code: 我有以下JavaScript代码:

var greeting = function (name) {
console.log("Great to see you," + " " + name);
};

console.log(greeting("name"));

It printed: Great to see you, name undefined 打印:很高兴见到你,名字不确定

How to get rid of this "undefined"? 如何摆脱这种“不确定”?

Thanks. 谢谢。

The undefined is getting printed because, JavaScript functions return undefined , by default, if we don't explicitly return anything. undefined正在打印,因为如果我们不显式返回任何内容,则JavaScript函数默认会返回undefined In your greeting function, you are logging the string and not returning anything. greeting函数中,您正在记录字符串,并且不返回任何内容。

So, two ways to fix this. 因此,有两种方法可以解决此问题。

  1. Return the string from greeting function like this 像这样从greeting函数返回字符串

     return "Great to see you, " + name; 

    Note: As @nnnnnn mentioned in the comments, you don't have to concatenate an extra space character. 注意:正如@nnnnnn在评论中提到的那样,您不必连接多余的空格字符。 You can simply include it as part of the previous string, like shown in this answer. 您可以简单地将其包括在上一个字符串中,如该答案所示。

  2. Or, simply don't log the output of greeting and simply call it like this 或者,根本不记录greeting的输出,而只是这样调用

     greeting("name"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM