【发布时间】:2015-04-08 01:09:11
【问题描述】:
我正在尝试阅读Zepto.js 的源代码。而且函数matches中有一个地方我不明白:
zepto.matches = function(element, selector) {
if (!selector || !element || element.nodeType !== 1) return false
var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
element.oMatchesSelector || element.matchesSelector
if (matchesSelector) return matchesSelector.call(element, selector)
var match, parent = element.parentNode, temp = !parent
if (temp) (parent = tempParent).appendChild(element)
//Here is my question. This line used the `~`
match = ~zepto.qsa(parent, selector).indexOf(element)
temp && tempParent.removeChild(element)
return match
}
函数matches 用于确定元素是否与提供的选择器匹配。它应该返回一个布尔值。
zepto.qsa() 是 Zepto 的 CSS 选择器实现,它使用 document.querySelectorAll 和其他一些优化。
所以。下面代码中~的作用是什么?
match = ~zepto.qsa(parent, selector).indexOf(element)
我知道~ 的意思是Bitwise NOT。
并且(根据我自己的测试):
~ -1 === 0
~ 0 === -1
~ 1 === -2
但我还是不明白这个设计是干什么用的。
谁能解释一下?
【问题讨论】:
-
如果您知道它是按位 NOT,那么问题出在哪里? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
马成,数字在javascript中可以是布尔值,因为它是动态类型的。零是假的,其他所有整数都等价于真。此函数使用按位 NOT 对 indexOf() 的结果和 javascript 中整数的真实性进行运算的方式来工作。
-
@MikeD。谢谢!我现在意识到了。我被它弄糊涂了。
标签: javascript zepto