javascript返回函数返回undefined

时间:2014-07-10 15:40:44

标签: javascript return expression

有人可以解释为什么我的三个示例函数中的第一个(ref failFunc())应该返回一个未定义的值而不是一个有效的字符串吗?

我知道我可以通过将表达式包装在括号(ref worksFunc1())中或将结果放在中间变量(ref worksFunc2())中来解决问题,但事实上第一个函数未能返回字符串违背了我在其他编程语言中经历的任何事情。

小提琴在这里: http://jsfiddle.net/BloodBaz/zGLmy/

JavaScript的:

var rs = {};

rs.failFunc = function(n)
{
    var h = "0010";
    var m = "15";
    var s = "12";
    var c = "10";

    return 
        h.substr(h.length - 4) + ":" + 
        m.substr(m.length - 2) + ":" + 
        s.substr(s.length - 2) + "." + 
        c.substr(c.length - 2);
}
rs.worksFunc1 = function(n)
{
    var h = "0010";
    var m = "15";
    var s = "12";
    var c = "10";

    return (
        h.substr(h.length - 4) + ":" + 
        m.substr(m.length - 2) + ":" + 
        s.substr(s.length - 2) + "." + 
        c.substr(c.length - 2));
}
rs.worksFunc2 = function(n)
{
    var h = "0010";
    var m = "15";
    var s = "12";
    var c = "10";

    var res =
        h.substr(h.length - 4) + ":" + 
        m.substr(m.length - 2) + ":" + 
        s.substr(s.length - 2) + "." + 
        c.substr(c.length - 2);
    return res;
}


var res = rs.failFunc();
document.getElementById('output1').innerHTML = res;
var res = rs.worksFunc1();
document.getElementById('output2').innerHTML = res;
var res = rs.worksFunc2();
document.getElementById('output3').innerHTML = res;

HTML:

<div id='output1'>output</div>
<div id='output2'>output</div>
<div id='output3'>output</div>

输出:

undefined
0010:15:12.10
0010:15:12.10

1 个答案:

答案 0 :(得分:4)

JavaScript语法很奇怪。一个特别奇怪的部分是,return语句后跟换行符被视为return;。没有表达式的return意味着对调用者而言,返回值为undefined

因此,

return 
    h.substr(h.length - 4) + ":" + 
    m.substr(m.length - 2) + ":" + 
    s.substr(s.length - 2) + "." + 
    c.substr(c.length - 2);

实际上与

相同
return;
    h.substr(h.length - 4) + ":" + 
    m.substr(m.length - 2) + ":" + 
    s.substr(s.length - 2) + "." + 
    c.substr(c.length - 2);

Read all about it in the language spec.