Open Hongbusi opened 2 years ago
function findTheTopThreeElements () { const elements = document.querySelectorAll('*') const map = {} elements.forEach(el => { map[el.tagName] ? map[el.tagName] += 1 : map[el.tagName] = 1 }) const sortEdArr = Object.keys(map).map(key => { return [ key, map[key] ] }).sort((a, b) => b[1] - a[1]) return sortEdArr.splice(0, 3) }
@guzao 可以看一下 md 语法 - 代码高亮。
ts版本,根据@alexzhang1030版改编
function topThreeTagName() {
type ReduceReturnType = {
[s: string]: number
};
Object.entries(
Array.from(document.querySelectorAll("*"))
.map(node => node.tagName)
.reduce<ReduceReturnType>((result, tag) => {
if (tag in result) {
result[tag] += 1;
} else {
result[tag] = 1;
}
return result
}, {}))
.sort((a, b) => b[1] - a[1])
.slice(0, 3)
}
先说结论:
看不懂?没关系,我们一步一步走,以百度为例吧
1. 拿到所有的标签
其实分为了三步:
现在它长这个样子:
2. 统计标签出现的次数
下面我们需要使用
reduce
来进行遍历,根据mdn
对于 reduce 语法的描述我们可以通过构造一个对象来统计,key 是 tagName,value 是出现的次数
现在它长这样:
3. 排序
现在,我们需要通过 mapping 的 value 进行排序,通过
mdn
对于Object.entries()
的用法描述:得知,我们可以通过返回的数组的第 1 项值来进行排序
现在它长这样:
4. 截取前 3 位
最终我们得出答案: