出现次数最多的 HTML 标签
这是一道前端基础与编程功底具备的面试题:
如果你前端基础强会了解 document.querySelector(*) 能够列出页面内所有标签 如果你编程能力强能够用递归快速实现同等的效果 有三种 API 可以列出页面所有标签:
- document.querySelector('*'),标准规范实现
- $$('*'),devtools 实现
- document.all,非标准规范实现
使用 document.querySelectorAll 实现如下
const maxBy = (list, keyBy) =>
list.reduce((x, y) => (keyBy(x) > keyBy(y) ? x : y));
function getFrequentTag() {
const tags = [...document.querySelectorAll("*")]
.map((x) => x.tagName)
.reduce((o, tag) => {
o[tag] = o[tag] ? o[tag] + 1 : 1;
return o;
}, {});
return maxBy(Object.entries(tags), (tag) => tag[1]);
}
使用 element.children 递归迭代如下 (最终结果多一个 document)
function getAllTags(el = document) {
const children = Array.from(el.children).reduce(
(x, y) => [...x, ...getAllTags(y)],
[]
);
return children;
}
// 或者通过 flatMap 实现
function getAllTags(el = document) {
const children = Array.prototype.flatMap.call(el.children, (x) =>
getAllTags(x)
);
return [el, ...children];
}