Boolan(!x)和布尔值(x == 0)之间的区别? [英] Difference between Boolan(!x) and Boolean(x==0)?

查看:161
本文介绍了Boolan(!x)和布尔值(x == 0)之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Code-snippet 1:

Code-snippet 1:

if ( !x ) { /* do stuff */ }

Code-snippet 2:

Code-snippet 2:

if ( x == 0 ) { /* do stuff */ }

对于什么值 x 这两个代码片段有何不同?

For what values of x do these two code-snippets differ?

我问,因为虽然我在规范中阅读了 == 的章节,但我仍然觉得很难处理上面的情况(它与ToBoolean强制相结合)。

I am asking because, although I read the chapter on == in the spec, I still find it hard to deal with situations like the above (where it is combined with ToBoolean coercion).

顺便说一句,我想知道这只是为了了解它(我想了解语言),所以不要再费心告诉我 === 或者问我 x 是什么。

btw, I want to know this just for the sake of knowing it (I want to understand the language), so don't bother telling me about === or asking me what x is.

更新: 我更正了第一个片段。我的意思是!x

推荐答案

以下内容将为您提供 true 为第一个, false 为第二个片段:

The following will give you true for the first and false for the second snippet:


  • NaN

  • null

  • undefined

  • NaN
  • null
  • undefined

这些会给你<第一个片段的code> false 和第二个片段的 true

And these will give you false for the first and true for the second snippet:


  • []

  • 0以及使用<$ c $转换为0的任何其他字符串c> Number(x),例如00,000,+ 0和-0(我现在称之为noughty strings)

  • 一个包含单个元素的数组,该元素是 0 null undefined 或空字符串或空字符串。

  • []
  • "0" and any other string that converts to 0 using Number(x) such as "00", "000", "+0", and "-0" (which I will now call "noughty strings")
  • an array containing a single element that is 0, null, undefined or an empty or noughty string.

对于其他所有内容,您将获得两个片段相同的结果,虽然可能还有一两件我没想过的案例。

For everything else you'll get the same result for both snippets, although there may be one or two more cases I haven't thought of.

这篇关于Boolan(!x)和布尔值(x == 0)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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