JavaScript函数末尾的Return语句

JavaScript函数末尾的Return语句,javascript,Javascript,我曾多次在JavaScript代码中看到人们在末尾添加return true,尽管这不是必需的。有人知道为什么吗 var _globalString; function doSomething() { _globalString= _globalString +' do something'; //some codes to do something more //finally adding a return true return true; } 可能让一

我曾多次在JavaScript代码中看到人们在末尾添加
return true
,尽管这不是必需的。有人知道为什么吗

var _globalString;
function doSomething()
{
    _globalString= _globalString +' do something';
    //some codes to do something more

    //finally adding a return true
    return true;
}

可能让一些人养成习惯的是表单的事件处理程序,如果有,可以说:

<form onsubmit="return myfunction();">


myfunction()
返回true,则表单提交,否则如果返回false则不提交。一般来说,这样做的人可能会养成这种习惯。有些语言需要函数返回值,Javascript不需要;在大多数函数的末尾使用
return true
是没有用的。

实际上,如果您在onsumbit事件中调用该函数

范例

<input type=sumit value=click Onsumbit='return function_name();">
除了埃里克的回答,我还要补充一点


返回真值/返回假值在需要布尔值作为返回值时也会使用。根据这个返回,您可以执行其他一些函数。

很难说为什么有些程序员会做某些事情

可能是为了表示成功/失败,但他们还没有添加任何失败的分支?

函数中的“返回”会自动停止该函数的进一步执行,例如:

function myFunc(){
    if(foo == 'bar'){
     /* do something */
    }else{
     /* do something */
    }
}
同:

function myFunc(){
    if(foo == 'bar'){
        /* do something */
        return true;
    }

    /* if foo != 'bar' then whatever follows is executed... */

}

此外,在下面的这种情况下,您不需要使用return true或false

var newPage = "http://www.google.com";
function redirectURL(){
   window.location.href= newPage;
   return true;      //no return required
}

没有回答这个问题,这个问题是关于函数末尾返回true的。也许没有,但它确实通过搜索“return true javascript”帮助到这里的人