javascript JS 警报显示“未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19317550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:08:55  来源:igfitidea点击:

JS Alert showing 'undefined'

javascript

提问by Lee Brindley

Hi there,

你好呀,

I just moved from C#/C++ to JavaScript last night, and am loving it!

我昨晚刚从 C#/C++ 转到 JavaScript,我很喜欢它!

I've just come across some behavior that I don't understand, wondering if anyone can shed some light on it?

我刚刚遇到了一些我不明白的行为,想知道是否有人可以对此有所了解?

When I call this script, I'm getting the expected alert box showing '5.5', however after that box is closed I get another alert simply showing "undefined", can anyone shed any light on this?

当我调用这个脚本时,我得到了显示“5.5”的预期警报框,但是在该框关闭后,我收到另一个显示“未定义”的警报,有人能对此有所了解吗?

Code below:

代码如下:

var myObj = {

age : 5,
weight : 5.5,

toString : function(){
    alert(this.weight);
}

}

alert(myObj.toString());

Many thanks

非常感谢

回答by nnnnnn

Your code calls alert()twice.

您的代码调用了alert()两次。

The first alert is the one displaying this.weight. But then the second displays whatever value is returned from the myObj.toString()function, and since you've coded that function without an explicit return value it returns undefinedby default.

第一个警报是显示this.weight. 但是第二个显示从myObj.toString()函数返回的任何值,并且由于您对该函数进行了编码而没有显式返回值,因此undefined默认情况下返回。

Normally a .toString()function would actually return a string, so you should do this:

通常一个.toString()函数实际上会返回一个字符串,所以你应该这样做:

toString : function(){
    return this.weight.toString();
}

Then you'll just get the one alert, as shown here: http://jsfiddle.net/eph7x/

然后你会得到一个警报,如下所示:http: //jsfiddle.net/eph7x/

And indeed then you can simply use:

事实上,你可以简单地使用:

alert(myObj);

...because your custom .toString()will get called automatically.

...因为您的自定义.toString()将被自动调用。