繁体   English   中英

javascript function 返回的结果与预期不同

[英]javascript function return different result than expected

在这个网站

https://www.worldometers.info/coronavirus/

我用这个javascript function 知道表中国家的position

{
    function findMatchingRow(word) {
        const found = []
        const trList = document.querySelectorAll('#main_table_countries_today > tbody > tr')
        trList.forEach((tr, i) => {
            if (tr.textContent.match(word)) {
                found.push({
                    index: i,
                    content: tr.textContent
                })
            }
        });
        return found
    }
    const matches = findMatchingRow("Australia")
    console.log(matches)

    if (matches.length > 0) {
        console.log('found at:', matches.map(m => m.index))
    }
}

仅对于澳大利亚,它返回 8 而不是 35

对于像波兰这样的其他国家,它给出了正确的数字,

我还是想不通

任何帮助将不胜感激 !

您不必从整行中获取文本内容,您只需匹配第一个td内容即可。 tr的任何地方都有像澳大利亚这样的地方。 所以缩小搜索范围。

function findMatchingRow(word) {
  const trList = [...document.querySelectorAll(
    "#main_table_countries_today > tbody > tr"
  )];
  let found;
  trList.some((tr, i) => {
    const name = tr.children[0].textContent.trim();
    if (name.includes(word)) {
      found = {
        index: i,
        content: tr.textContent,
      };
    }
    return found;
  });
  return found;
}
const found = findMatchingRow("Australia");

if (found) {
  console.log("found at:"+ JSON.stringify(found));
  console.log("found at:"+ found.index);
}

您只搜索整个 tr (行)的文本内容。 text-Content 都是节点。 澳大利亚导致一个数组,因为许多条目将“澳大利亚/大洋洲”作为数据大陆属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM