return !1 in javascript

return !1 in javascript

本文关键字:javascript in return      更新时间:2023-09-26

我刚刚在javascript中遇到一个函数,它有return !1

我只是想知道这到底是什么意思?

为什么你要return !1return !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逻辑非操作符-中声明,当您在前面放置感叹号!时,结果将被计算为布尔值,并返回相反的值。

的例子:

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中搜索,例如

这种返回truefalse的方式似乎特别愚蠢

下面是验证代码:

  • 在这些情况下不返回或不做任何事情:"case 1", "case true", "case yes", "case y", "Case 1"
  • "case !0"返回"true"
  • 当以上情况都不满足时,默认返回"false"