如何用JavaScript遍历类别并合并多组JavaScript库名称为单个数组?
解决方法:用数组方法简化爬虫并合并结果
Got it, let's clean up your code and get that single array of library names you need! Your current approach repeats a lot of logic, and we can fix that with querySelectorAll and array methods like map(), flat(), and filter() to streamline the process.
完整可运行代码
// 获取页面上所有的分类标题 const categoryHeadings = document.querySelectorAll('.mw-headline'); // 处理每个分类,提取库名称并合并成单个数组 const allLibraryNames = Array.from(categoryHeadings) .map(heading => { // 获取当前分类对应的库列表元素(和你原代码的选择逻辑一致) const libraryGroup = heading.nextElementSibling.parentElement.nextElementSibling; // 拆分文本、清理内容并过滤掉无关行 return libraryGroup.textContent .split('\n') // 按换行符拆分每行内容 .map(line => line.trim()) // 去掉每行前后的空白字符 .filter(line => { // 过滤规则:跳过空行、"See also"提示、停用库的标题行 if (!line) return false; if (line.includes('See also:')) return false; if (line.includes('No longer actively developedEdit')) return false; return true; }); }) .flat() // 将多个分类的数组合并为一个一维数组 .filter((library, index, self) => self.indexOf(library) === index); // 可选:去重,移除重复出现的库 // 输出结果到控制台 console.log(allLibraryNames);
代码解释
document.querySelectorAll('.mw-headline'):一次性获取所有分类标题,替代你手动逐个选择第0到第8个标题的重复代码,更灵活也避免了手动复制错误(比如你原代码里ninthGroup误用secondTitle的问题)。Array.from(categoryHeadings):把浏览器返回的NodeList转换为普通数组,这样就能使用数组的map()等方法。map(heading => {...}):遍历每个分类标题,处理对应的库列表内容,这就是你想要用的map()函数的正确用法。- 文本清理与过滤:把每个分组的文本拆分成单行,去掉空白字符,再过滤掉非库名称的行(比如提示文本、空行)。
flat():这是合并多个数组成单个数组的关键!它会把二维数组(每个分类一个数组)扁平化成为一维数组。- 最后一个
filter():可选步骤,用来移除重复出现的库名称(比如某些库会出现在多个分类下),如果不需要去重可以直接删掉这一行。
运行效果
执行后你会得到一个干净的数组,只包含所有库的名称文本,没有分类信息、空白字符或重复项。
内容的提问来源于stack exchange,提问作者Peter Havel
相关产品推荐
相关产品推荐

