我绝不是 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/
相关文章:
html - 有人可以解释 HTML5 aria-* 属性吗?
html - 如何设置 dt 和 dd 的样式,使它们在同一行?
?">javascript - 哪些浏览器支持<script async ="async"/>?
javascript - 就 HTML 文件路径位置而言, "./"(点斜杠)指的是什么?
javascript - 可以即时进行语法突出显示的文本区域?
html - 如何在多行 flexbox 布局中指定换行符?