简体   繁体   中英

javascript return function returns undefined

Can anyone explain why the first of my three sample functions (ref failFunc() ) should return an undefined value rather than a valid string?

I know I can fix the problem by wrapping the expression in brackets (ref worksFunc1() ) or placing the result in an intermediate variable (ref worksFunc2() ) but the fact the first function failed to return a string goes against anything I've experienced in other programming languages.

Fiddle is here: 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>

OUTPUT:

undefined
0010:15:12.10
0010:15:12.10

JavaScript syntax is strange. One particularly odd part is that a return statement followed by a newline is taken to be return; . A return without an expression means that to the caller, the return value is undefined .

Thus,

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

is effectively the same as

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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