有人可以解释这种“双重否定”的伎俩吗? [英] Can someone explain this 'double negative' trick?

查看:125
本文介绍了有人可以解释这种“双重否定”的伎俩吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绝对不是Javascript的专家,但我一直在阅读Mark Pilgrim的潜入HTML5网页他提到了一些我想要更好理解的东西。



他说:


最后,您使用双重否定技巧将结果强制为布尔值(true或false)。




 函数supports_canvas(){
return !! document.createElement('canvas')。getContext;

$ / code>

如果有人能更好地解释这一点,我将不胜感激!

解决方案

逻辑NOT运算符将值转换为相反的布尔值它的逻辑价值。



第二个将前一个布尔结果转换回其原始逻辑值的布尔表示。



从这些文档对于逻辑NOT运算符:


如果其单个操作数可以转换为true,则返回false;如果 getContext 给你一个假,那么值, !! 将使它返回布尔值 false 。否则它将返回 true



falsey值为:


  • false

  • NaN

  • undefined

  • null
  • (空字符串)

  • 0


I am by no means an expert at Javascript, but I have been reading Mark Pilgrim's "Dive into HTML5" webpage and he mentioned something that I would like a better understanding of.

He states:

Finally, you use the double-negative trick to force the result to a Boolean value (true or false).

function supports_canvas() {
  return !!document.createElement('canvas').getContext;
}

If anyone can explain this a little better I would appreciate it!

解决方案

A logical NOT operator ! converts a value to a boolean that is the opposite of its logical value.

The second ! converts the previous boolean result back to the boolean representation of its original logical value.

From these docs for the Logical NOT operator:

Returns false if its single operand can be converted to true; otherwise, returns true.

So if getContext gives you a "falsey" value, the !! will make it return the boolean value false. Otherwise it will return true.

The "falsey" values are:

  • false
  • NaN
  • undefined
  • null
  • "" (empty string)
  • 0

这篇关于有人可以解释这种“双重否定”的伎俩吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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