JS 中的标题提取 - "If" 有效但 "Else" 无效

Headings extraction in JS - "If" works but "Else" doesn't

我正在尝试 运行 此代码并提取所有标题,并在某些标题不存在时显示“不存在”选项...不存在,但它没有阅读其他内容以某种方式声明,如果你能指出正确的方向,那就太好了。

function headingsEx() {
    let h = ["h1", "h2", "h3", "h4", "h5", "h6"];
    for (let i of h) {
        if (document.getElementsByTagName(i)) {
            let foundHs = document.querySelectorAll(i)
            for (let c of foundHs) {
                console.log({ [i]: c.textContent })
            };
        } else {
            console.log([i] + " doesn't exist");
        }
    }
}

headingsEx();

根据 the docsdocument.getElementsByTagName(i) returns 一个实时 HTMLCollection。文档中没有其他地方说 returns 除此以外的任何内容。所以可以肯定地说 document.getElementsByTagName(i) 永远是真实的(即不是 nullfalse)。您可以改为检查 length 成员。如果至少存在一个元素,它将大于 0

function headingsEx() {
    let h = ["h1", "h2", "h3", "h4", "h5", "h6"];
    for (let i of h) {
        if (document.getElementsByTagName(i).length) {
            let foundHs = document.querySelectorAll(i)
            for (let c of foundHs) {
                console.log({ [i]: c.textContent })
            };
        } else {
            console.log([i] + " doesn't exist");
        }
    }
}

headingsEx();

由于您询问了替代方法:

此示例使用 querySelectorAll, and then uses map 获取所有标题元素以创建一个新的节点名称数组。然后您可以遍历标题数组并检查每个元素是否包含在 nodeNames 数组中,然后相应地记录结果。

const arr = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
const headings = document.querySelectorAll(arr.join(','));

const nodeNames = [...headings].map(heading => {
  return heading.nodeName.toLowerCase();
});

arr.forEach(el => {
  if (nodeNames.includes(el)) {
    console.log(`${el}: exists.`)
  } else {
    console.log(`${el}: does not exist.`)
  }
});
<h1>Hi</h1>
<h3>Hi</h3>
<h4>Hi</h4>
<h6>Hi</h6>

一个空数组是真实的(通常无论如何)所以即使 getElementsByTagName(i) 什么也没找到并且 returns 一个空数组,“then”块仍然被执行。

console.log('is [] true?');
if ([]) {
  console.log('yes');
} else {
  console.log('no');
}

console.log('---');

console.log('is [99] true?');
if ([99]) {
  console.log('yes');
} else {
  console.log('no');
}

如果您想知道我为什么说“通常”,请参阅 https://xavierchow.github.io/2015/12/15/js-coercion/ 但如果您听不懂也不要担心。这对我来说也是个新闻。