javascript函数返回与预期不同的结果

javascript函数返回与预期不同的结果,javascript,Javascript,在本网站 我使用这个javascript函数来了解国家在表中的位置 { function findMatchingRow(word) { const found = [] const trList = document.querySelectorAll('#main_table_countries_today > tbody > tr') trList.forEach((tr, i) => { i

在本网站

我使用这个javascript函数来了解国家在表中的位置

{
    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(行)的文本内容。文本内容是所有节点。Australia生成一个数组,因为许多条目将“Australia/Oceania”作为数据大陆属性。

当您说它返回8而不是36时,您的意思是什么?为什么它应该返回36?请张贴相关的HTML以及@WillD Hemeans
匹配。长度从36变为8。您只计算行数。如果一行有
Australia
多次,它将只返回一次。@Barmar它将不会有重复的国家/地区名称。您能解释一下问题是什么以及您是如何解决的吗?添加
.trim()
无助于此。如果修剪的字符串包含匹配项,则未修剪的字符串也包含匹配项。我添加了详细信息。这是我通常遵循的任何TD,你也可以直接匹配。没有空间。缩小搜索范围将如何使其返回更多结果?国家列表中只有一个澳大利亚。解决方案应该优化。我补充了一些细节。问题是什么?他/她可以找到更好的解决方案。根据他的要求,他们希望阵列中有36个匹配项,但他们只得到8个匹配项。缩小搜索范围将如何获得所有36个匹配项?哦,好吧,我想我现在明白了,那么我如何才能选择特定的行?