Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在coffeescript中使用单等号执行while循环_Coffeescript - Fatal编程技术网

在coffeescript中使用单等号执行while循环

在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

我试图在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.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。