javascript 返回无效0;vs 回报;

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

return void 0; vs return;

javascriptunderscore.js

提问by Lukasz Prus

I'm studying the annotated source code of Underscore.js.

我正在研究 Underscore.js 的带注释的源代码。

http://underscorejs.org/docs/underscore.html#section-41

http://underscorejs.org/docs/underscore.html#section-41

Here's the _.first method:

这是 _.first 方法:

  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n == null) || guard ? array[0] : slice.call(array, 0, n);
  };

Question:

问题:

Why 'return void 0;' and not just 'return;' ?As far as I know returnimplicitly returns undefined (the value!) from a function. Just like 'return void 0' does.

为什么'返回无效0;' 而不仅仅是“回报;” ? 据我所知,return从函数中隐式返回 undefined (值!)。就像'return void 0'一样。

采纳答案by Daff

In the MDN reference for the void operatorit states:

void 运算符MDN 参考中,它指出:

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

void 运算符通常仅用于获取未定义的原始值,通常使用“void(0)”(相当于“void 0”)。在这些情况下,可以使用全局变量 undefined 代替(假设它没有被分配给一个非默认值)。

So it is indeed equivalent to undefinedbut the problem with the undefinedvariable is that it can be redefined as something else. Personally I would always simply return;because it consistently yields the exact same result (as in: (function() {})() === void 0).

所以它确实等同于undefinedundefined变量的问题在于它可以重新定义为其他东西。就我个人而言,我总是简单地return;因为它始终产生完全相同的结果(如:)(function() {})() === void 0

Clarification

澄清

Since some commenter consider this not an appropriate answer:

由于一些评论者认为这不是一个合适的答案:

(function() {})() === void 0always yields true which means that it is exactly the same as return;. So you can consider this an inconsistency in the Underscore library as plain return statements are used in other places (yes, even there it can happen).

(function() {})() === void 0总是产生真,这意味着它与 完全相同return;。因此,您可以认为这是 Underscore 库中的不一致,因为其他地方使用了简单的 return 语句(是的,即使在那里也可能发生)。

Minification and optimization

缩小和优化

Another addendum, it looks as if it also doesn't optimize any better during minification. Using the closure compilerthe return void 0;vs return;version of the above code sample is still about 5% bigger.

另一个附录,它看起来好像在缩小过程中也没有优化得更好。使用闭包编译器,上述代码示例的return void 0;vsreturn;版本仍然大了大约 5%。