在 JavaScript 中返回 !1 [英] return !1 in javascript

查看:24
本文介绍了在 JavaScript 中返回 !1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have just come across a function in javascript which has return !1

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

I was just wondering what this actually meant?

你为什么要return !1return !0

有人可以解释一下这是什么意思吗?

Could someone please explain what it means please?

这是我遇到的函数:

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
  • return !1 is equivalent to return false
  • return !0 is equivalent to return true

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

In the specification - 11.4.9 Logical NOT Operator - it states that when you place an exclamation mark ! in front, the result is evaluated as Boolean and the opposite is returned.

示例:

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 优化器 传递的代码中看到这一点.我认为这样做主要是为了实现代码的简洁性.

I mostly see this in a code passed through Google's JS optimiser. I think it is mostly done to achieve shortness of the code.

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

It is often used when a strictly Boolean result is needed - you may see something like !!(expression). Search in jQuery, for example.

这篇关于在 JavaScript 中返回 !1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆