Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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
Javascript 如何将Array.from与XPathResult一起使用?_Javascript_Arrays_Xpath - Fatal编程技术网

Javascript 如何将Array.from与XPathResult一起使用?

Javascript 如何将Array.from与XPathResult一起使用?,javascript,arrays,xpath,Javascript,Arrays,Xpath,使用querySelectorAll时,我可以在示例文档中找到138个td节点 Array.from(document.querySelectorAll('td')).length 138 当我对XPath执行相同操作时,没有得到任何结果: Array.from(document.evaluate(".//td", document.body, null, XPathResult.ANY_TYPE, null)).length 0 尽管至少存在一个匹配项: document.evaluate

使用
querySelectorAll
时,我可以在示例文档中找到138个
td
节点

Array.from(document.querySelectorAll('td')).length
138
当我对XPath执行相同操作时,没有得到任何结果:

Array.from(document.evaluate(".//td", document.body, null, XPathResult.ANY_TYPE, null)).length
0
尽管至少存在一个匹配项:

document.evaluate(".//td", document.body, null, XPathResult.ANY_TYPE, null).iterateNext().nodeName
"TD"
问题似乎是
Array.from
无法迭代
XPathResult
。即使这样,也会返回0:

Array.from(document.evaluate('.', document.body, null, XPathResult.ANY_TYPE, null)).length
0
如何使
XPathResult
适合
数组。从
开始?

很遗憾,您不能。可以将两种类型的对象转换为数组:

  • 具有
    .length
    属性的“类似数组”的
  • 那些实现迭代器协议并允许您获取其所有元素的
  • XPathResult
    不执行这些操作。您可以通过手动迭代结果并将结果存储在数组中来完成此操作,例如:

    const nodes = [];
    let node = xPathResult.iterateNext();
    while (node) {
      nodes.push(node);
      node = xPathResult.iterateNext();
    }
    
    …但如果要在节点上循环,则可能可以在循环中执行任何想要执行的数组操作。

    为了避免重复并(imo)使其更清晰,可以改为执行
    const nodes=[];let节点;while(node=xPathResult.iterateNext()){nodes.push(node);}
    。太糟糕了,你不能只说
    while(const node=xPathResult.iterateNext()){…}
    ,因为这个值没有在循环外使用。