简体   繁体   English

函数的目的仅返回布尔值

[英]Purpose of Function returns only boolean

Somewhere in jQuery I have seen 2 functions that returns only boolean like below. 我在jQuery的某个地方看到了2个仅返回boolean函数,如下所示。

function h(){
   return !0;
}

function r(){
   return !1; 
}

What is the purpose of doing this, while Boolean can be written directly? 这样做的目的是什么,而Boolean可以直接编写呢?

Economy of characters. 经济的字符。

Having a 3 character function that returns true or false takes less characters than doing an exact comparison. 具有3个字符的函数返回true或false的字符比进行精确比较所需的字符少。

var a = false;
if (a === r()) console.log('3 characters instead of 5')

Large libraries usually alias commonly used globals like undefined and window as well for minification. 大型库通常会别名化常用的全局变量(例如undefinedwindow以实现最小化。

For example, you may see something like 例如,您可能会看到类似

(function($, a, b) { ... })(jQuery, window, undefined)

0 is falsey and 1 is truthy. 0为假, 1为真。

So, there is no need to convert them to boolean unless they are used in code like 因此,除非将它们用于类似如下的代码中,否则无需将它们转换为布尔值

if (h() === false) {

Or code converted when the code is minified as true and false are minified to !1 and !0 respectively. 或将代码最小化为truefalse时转换的代码分别最小化为!1!0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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