在javascript中返回!1

Dar*_*tis 17 javascript return function

我刚刚遇到一个javascript函数 return !1

我只是想知道这究竟是什么意思?

你为什么return !1或者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
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Bak*_*dan 18

立即回答您的问题:

  • return !1 相当于 return false
  • return !0 相当于 return true

在规范中 - 11.4.9逻辑NOT运算符 - 它指出当您!在前面放置一个感叹号时,结果将被计算为布尔值,并返回相反的结果.

示例:

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"
Run Code Online (Sandbox Code Playgroud)

我通常在通过Google的JS优化器传递的代码中看到这一点.我认为这主要是为了实现代码的短缺.

它通常在需要严格的布尔结果时使用 - 您可能会看到类似的结果!!(expression).例如,在jQuery中搜索.

  • @Mike是的,它会,但那么它将是一个数字,而不是布尔值. (5认同)
  • 但是为什么要使用 !1 而不是 0?0 会更短,不是吗? (2认同)

spe*_*der 11

这似乎是返回一个特别愚蠢的方式truefalse

  • 2个字节对​​4(或假为5).下载Javascript需要的带宽更少!:P (13认同)