我刚刚在 JavaScript 中遇到了一个函数,它有return !1
.
这实际上意味着什么?你为什么要return !1
or return !0
?
这是我遇到的函数:
function convertStringToBoolean(a) {
typeof a == "string" && (a = a.toLowerCase());
switch (a) {
case "1":
case "true":
case "yes":
case "y":
case 1:
case !0:
return !0;
default:
return !1
}
}
立即回答您的问题:
-
return !1
相当于return false
-
return !0
相当于return true
在规范中 -11.4.9 逻辑非运算符- 它指出当您放置感叹号时!
在前面,结果被评估为布尔值并返回相反值。
Example:
var a = 1, b = 0;
var c = a || b;
alert("c = " + c + " " + typeof c); // here typeof c will be "number"
a = !0, b = !1;
c = a || b;
alert("c = " + c + " " + typeof c); // here typeof c will be "boolean"
我主要在通过 Google 传递的代码中看到这一点JS优化器。我认为这主要是为了实现代码的简短。
当需要严格的布尔结果时经常使用它 - 你可能会看到类似的东西!!(expression)
。例如,在 jQuery 中搜索。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)