Javascript 使用不返回任何内容的 return 语句有什么好处吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3717420/
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-08-23 05:50:46  来源:igfitidea点击:

Is there a benefit to using a return statement that returns nothing?

javascriptrefactoringreturn-value

提问by Stephen

I'm refactoring a large javascript document that I picked up from an open source project. A number of functions use inconsistent return statements. Here's a simple example of what I mean:

我正在重构一个从开源项目中获取的大型 JavaScript 文档。许多函数使用不一致的返回语句。这是我的意思的一个简单示例:

var func = function(param) {
    if (!param) {
        return;
    }
    // do stuff
    return true;
}

Sometimes the functions return boolean, sometimes strings or other things. Usually they are inconsistently paired with a simple return;statement inside of a conditional.

有时函数返回布尔值,有时返回字符串或其他东西。通常,它们与return;条件语句中的简单语句不一致地配对。

The problem is that the code is complex. It is a parser that uses a multitude of unique RegEx matches, creates and destroys DOM nodes on the fly, etc. Preliminary testing shows that, in the above example, I could change the return;statement to become return false;, but I'm concerned that I may not realize that it had a negative impact (i.e. some feature stopped working) on the script until much later.

问题是代码很复杂。它是一个解析器,它使用大量独特的 RegEx 匹配,动态创建和销毁 DOM 节点等。初步测试表明,在上面的示例中,我可以将return;语句更改为 become return false;,但我担心我可能会直到很久以后才意识到它对脚本产生了负面影响(即某些功能停止工作)。

So my questions: Is there a benefit to using a blank return statement? Could this have been intentionally coded this way or was it just lazy? Can I change them all to return false;, or return null;or do I need to dig through every call and find out what they are doing with the results of those functions?

所以我的问题是:使用空白的 return 语句有好处吗?这可能是故意以这种方式编码还是只是懒惰?我可以将它们全部更改为return false;,或者return null;我是否需要深入研究每个调用并找出它们对这些函数的结果做了什么?

回答by Guffa

Using returnwithout a value will return the value undefined.

return不带值使用将返回值undefined

If the value is evaluated as a boolean, undefinedwill work as false, but if the value for example is compared to false, you will get a different behaviour:

如果该值被评估为布尔值,undefined则将作为false,但如果将例如该值与 进行比较false,您将获得不同的行为:

var x; // x is undefined
alert(x); // shows "undefined"
alert(!x); // shows "true"
alert(x==false); // shows "false"

So, while the code should logically return trueor false, not trueor undefined, you can't just change return;to return false;without checking how the return value is used.

因此,虽然代码在逻辑上应该返回trueor false,而不是trueor undefined,但您不能return;return false;不检查返回值的使用方式的情况下更改为。

回答by Josh

"Blank return" statements can be used to transfer the control back to the calling function (or stop executing a function for some reason - ex: validations etc). In most cases I use blank return statement is when I'm doing some kind of a validation. However, I make it a point to set some indicator as to why the execution of the function is stopped. For example, set the "innerText" property on a DIV element with the error message.

“空白返回”语句可用于将控制权转移回调用函数(或由于某种原因停止执行函数 - 例如:验证等)。在大多数情况下,我在进行某种验证时使用空白 return 语句。但是,我强调设置一些指标来说明为什么停止执行函数。例如,在带有错误消息的 DIV 元素上设置“innerText”属性。

In the code above, it looks like it is a validation. The function returns a "true" if everything went well. It looks like the calling function parses the return value, and if it is "true", next step of statements (in the calling function) are executed.

在上面的代码中,它看起来像是一个验证。如果一切顺利,该函数将返回“true”。看起来调用函数会解析返回值,如果为“true”,则执行下一步(在调用函数中)的语句。

It is a good practice to return "false" instead of a blank return in the above example. That way you make it all uniform and make life easy for other programmers.

在上面的示例中返回“false”而不是空白返回是一个好习惯。这样你就可以统一一切,让其他程序员的生活更轻松。

You could fix such inconsistencies; however, make sure you test all the changes thoroughly. It is a good practice to test each change you make to the code, however small it may be.

您可以修复此类不一致;但是,请确保彻底测试所有更改。测试您对代码所做的每项更改都是一种很好的做法,无论更改有多小。

回答by Mark Schultheiss

What MIGHT be lost here (not direct with your example) is that you can then have a tri-state object:

这里可能丢失的(不是直接与您的示例)是您可以拥有一个三态对象:

var myfunc = function(testparam) {
    if (typeof testparam === 'undefined') return;
    if (testparam) {
        return true;
    }
    else {
        return false;
    }
};

var thefirst = myfunc(true)
var thesecond = myfunc(false);
var thelast = myfunc();
alert("type:" + typeof thefirst+" value:"+thefirst);
alert("type:" + typeof thesecond+" value:"+thesecond);  
alert("type:" + typeof thelast+" value:"+thelast); 

these return:

这些返回:

> type:boolean:true 
> type:boolean:false
> type:undefined:undefined

note: null would return false in this example myfunc(null);

注意:在此示例中,null 将返回 false myfunc(null);

回答by Q_Mlilo

Changing your functions will actually alter the code because return;and return false;output different data types.

更改您的函数实际上会改变代码,因为 return;return false;输出不同的数据类型。

var test = function (x) {
    if (!x) {
        return;
    }
    else {
        return false;
    }
};

var a = test(true), b = test(false);

console.log(typeof b); // boolean
console.log(typeof a); // undefined  

回答by T.J. Crowder

There is no difference at all between return;and return undefined;. The result of calling both functions is to receive the value undefined.

return;和之间完全没有区别return undefined;。调用这两个函数的结果是接收值undefined

(There's a very smallspecification-level difference between a function body that terminates with returnvs. just falling off the end of the code, but it's nothing that can be detected in code.1 Calling a function where execution falls off the end of the code also results in the value undefined.)

(以终止于代码结尾的函数体与仅从代码末尾脱落的函数体之间存在非常小的规范级别差异return,但在代码中无法检测到。1 调用执行从代码末尾脱落的函数也会产生值undefined。)

"use strict";

// Implicit return of `undefined`
function x() {
    return;
}
// Explicit return of `undefined`
function y() {
    return undefined;
}
// Execution falls off the end
function z() {
}
console.log(typeof x() === "undefined"); // true
console.log(typeof y() === "undefined"); // true
console.log(typeof z() === "undefined"); // true



Unless, of course, something has shadowed undefined. Which is still sadly possible (though not, gladly, at global scope). In that veryedgy edge case, there's a difference:

除非,当然,有什么东西已经遮蔽了undefined。遗憾的是,这仍然是可能的(尽管不是,很高兴,在全球范围内)。在那个非常前卫的边缘情况下,有一个区别:

"use strict";
(function() {
    const undefined = 42;
//  ^^^^^^^^^^^^^^^---- shadowing `undefined`
    // Implicit return of `undefined`
    function x() {
        return;
    }
    // Explicit return of `undefined`
    function y() {
        return undefined;
    }
    // Execution falls off the end
    function z() {
    }
    console.log(typeof x() === "undefined"); // true, `x` returns the canonical `undefined`
    console.log(typeof y() === "undefined"); // false, `y` returns 42
    console.log(typeof z() === "undefined"); // true, `z` (effectively) returns the canonical `undefined`
})();



1 Using returnis an abrupt completionthat [[Call]] converts to a normal completion w/value. Falling off the end of the code is a normal completion(spec) (that [[Call]] ensures supplies undefinedfor the value). But again, this is a specification level difference, not something that's observable in code.

1 Usingreturn是一个突然完成,[[Call]] 转换为正常完成 w/value。从代码的末尾脱落是一个正常的完成规范)([[Call]] 确保undefined值的供应)。但同样,这是规范级别的差异,而不是在代码中可以观察到的东西。