先说结论:
Object.entries(Array.from(document.querySelectorAll("*")).map(v => v.tagName).reduce((res, a) => ((res[a] = (res[a] || 0) + 1), res), {})).sort((a, b) => b[1] - a[1]).slice(0, 3)
看不懂?没关系,我们一步一步走,以百度为例吧
其实分为了三步:
// 所有节点 const allNodes = document.querySelectorAll("*"); // 类数组重新构造 const nodeArr = Array.from(allNodes); // 获取所有的标签 const allTags = nodeArr.map(v => v.tagName);
现在它长这个样子:
下面我们需要使用 reduce 来进行遍历,根据 mdn 对于 reduce 语法的描述
reduce
mdn
reduce(callbackFn, initialValue)
我们可以通过构造一个对象来统计,key 是 tagName,value 是出现的次数
const tagCountMapping = allTags.reduce((res, a) => ((res[a] = (res[a] || 0) + 1), res), {})
现在它长这样:
现在,我们需要通过 mapping 的 value 进行排序,通过 mdn 对于 Object.entries() 的用法描述:
Object.entries()
const obj = { foo: 'bar', baz: 42 }; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
得知,我们可以通过返回的数组的第 1 项值来进行排序
const sortedTag = Object.entries(tagCountMapping).sort((a, b) => b[1] - a[1]);
最终我们得出答案:
const res = sortedTag.slice(0, 3)
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) }
Activity
alexzhang1030 commentedon Jun 30, 2022
先说结论:
看不懂?没关系,我们一步一步走,以百度为例吧
1. 拿到所有的标签
其实分为了三步:
现在它长这个样子:
2. 统计标签出现的次数
下面我们需要使用
reduce来进行遍历,根据mdn对于 reduce 语法的描述我们可以通过构造一个对象来统计,key 是 tagName,value 是出现的次数
现在它长这样:
3. 排序
现在,我们需要通过 mapping 的 value 进行排序,通过
mdn对于Object.entries()的用法描述:得知,我们可以通过返回的数组的第 1 项值来进行排序
现在它长这样:
4. 截取前 3 位
最终我们得出答案:
guzao commentedon Jun 30, 2022
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)
}
Hongbusi commentedon Jun 30, 2022
@guzao 可以看一下 md 语法 - 代码高亮。
likui628 commentedon Jun 30, 2022
ts版本,根据@alexzhang1030版改编