使用不返回任何内容的return语句有什么好处? [英] Is there a benefit to using a return statement that returns nothing?

查看:252
本文介绍了使用不返回任何内容的return语句有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

有时函数会返回布尔值,有时会返回字符串或其他内容。通常它们与条件内的简单 return; 语句不一致。

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

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

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.

所以我的问题:使用空白退货声明是否有好处?这可能是故意用这种方式编码还是只是懒惰?我可以将它们全部更改为 return false; ,或返回null; 或者我是否需要挖掘每个电话和找出他们对这些函数的结果做了什么?

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 没有值将返回值 undefined

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

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

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

因此,代码应该在逻辑上返回 true false ,而不是 true undefined ,你不能只是将 return; 更改为返回false; 而不检查返回值的使用方式。

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

这篇关于使用不返回任何内容的return语句有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆