Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

javascript - 有人能解释这个“双重否定”的伎俩吗? [重复](Can someone explain this 'double negative' trick? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

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.

(我绝不是Javascript的专家,但我一直在阅读Mark Pilgrim的“潜入HTML5”网页,他提到了一些我想要更好理解的内容。)

He states:

(他说:)

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

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

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

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

(如果有人能够更好地解释这一点我会很感激!)

  ask by ProfessionalAmateur translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A logical NOT operator !

(逻辑NOT运算符!)

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:

( Logical NOT运算符的这些文档中:)

Returns false if its single operand can be converted to true;

(如果单个操作数可以转换为true,则返回false;)

otherwise, returns true.

(否则,返回true。)

So if getContext gives you a "falsey" value, the !!

(所以如果getContext给你一个“假”值,那就!!)

will make it return the boolean value false .

(将使它返回布尔值false 。)

Otherwise it will return true .

(否则它将返回true 。)

The "falsey" values are:

(“假”值是:)

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

    ("" (空字符串))

  • 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...