gpt4 book ai didi

javascript - 有人可以解释这个 'double negative' 技巧吗?

转载 作者:IT老高 更新时间:2023-10-28 11:06:14 25 4
gpt4 key购买 nike

我绝不是 Javascript 方面的专家,但我一直在阅读 Mark Pilgrim 的 "Dive into HTML5"网页,他提到了一些我想更好地理解的东西。

他说:

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;
}

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

最佳答案

逻辑非运算符 ! 将值转换为与其逻辑值相反的 bool 值。

第二个 ! 将先前的 bool 结果转换回其原始逻辑值的 bool 表示。

From these docs对于逻辑非运算符:

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

所以如果 getContext 给你一个“假”值,!! 将使它返回 bool 值 false。否则它将返回 true

“虚假”值是:

  • NaN
  • 未定义
  • null
  • ""(空字符串)
  • 0

关于javascript - 有人可以解释这个 'double negative' 技巧吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com