成功调用带参数的简单函数后,带有“undefined”消息的意外警报

时间:2012-06-27 01:18:24

标签: javascript

任何人都可以告诉我为什么以下代码会生成我期望的警报框(RyeTofuRye),但是然后会生成第二个警告框,其中包含“未定义”消息?至少这是我在Windows 7机器上最新FireFox中所做的事情。

function makeSandwich(bread, meat) {
alert(bread + meat + bread);
}
var mySandwich = makeSandwich('Rye', 'Tofu');
alert(mySandwich);

4 个答案:

答案 0 :(得分:2)

当你没有返回时,第二个警告未定义!!
流程如下:

function makeSandwich(bread, meat) {//step-3
    alert(bread + meat + bread); // alerting RyeTofuRy, step-4
    // am i returnign anything? nope!
    //adding a return (bread + meat + bread); resolves teh problem though
    }

var mySandwich = makeSandwich('Rye', 'Tofu');//start here step-1
alert(mySandwich);//step-2, step-5

答案 1 :(得分:0)

由于您未从makeSandwich()返回值,因此mySandwichundefined

答案 2 :(得分:0)

将其更改为:

function makeSandwich(bread, meat) {
return(bread + meat + bread);
}
var mySandwich = makeSandwich('Rye', 'Tofu');
alert(mySandwich);

答案 3 :(得分:0)

makeSandwich什么都不返回。将其更改为:

function makeSandwich(bread, meat) {
    return(bread + meat + bread);
}