在coffeescript中使用单等号执行while循环
我试图在coffeescript中编写以下JS:在coffeescript中使用单等号执行while循环,coffeescript,Coffeescript,我试图在coffeescript中编写以下JS: x = 0; if(node.offsetParent) { do { x += node.offsetLeft; } while(node = node.offsetParent); } 这是我到目前为止得到的,但是节点似乎返回空值 if node.offsetParent loop x += node.offsetLeft break if typeof (node = node.offse
x = 0;
if(node.offsetParent) {
do {
x += node.offsetLeft;
} while(node = node.offsetParent);
}
这是我到目前为止得到的,但是节点似乎返回空值
if node.offsetParent
loop
x += node.offsetLeft
break if typeof (node = node.offsetParent) == "undefined"
x
问题很简单,当DOM元素
节点
没有偏移父节点时,节点.offsetParent
是空的
,而不是未定义的
。空的类型是'object'
,而不是'undefined'
为什么不采取与原始JS循环相同的方法,只需检查node.offsetParent
是否存在错误?那么您的代码可能看起来像:
x = 0
if node.offsetParent
loop
x += node.offsetLeft
break unless (node = node.offsetParent)
x
我还想指出,虽然CoffeeScript没有do..while
语法,但在本例中,您可以简单地使用while
循环,使您的if
多余:
x = 0
while node.offsetParent
x += node.offsetLeft
node = node.offsetParent
x
您的代码看起来是正确的。很抱歉,如果所说的节点变量返回null。