-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
如何在 console 中写代码,统计当前页面出现次数最多的三种标签 #25
Comments
先说结论: 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) 看不懂?没关系,我们一步一步走,以百度为例吧 1. 拿到所有的标签其实分为了三步: // 所有节点
const allNodes = document.querySelectorAll("*");
// 类数组重新构造
const nodeArr = Array.from(allNodes);
// 获取所有的标签
const allTags = nodeArr.map(v => v.tagName); 现在它长这个样子: 2. 统计标签出现的次数下面我们需要使用 reduce(callbackFn, initialValue) 我们可以通过构造一个对象来统计,key 是 tagName,value 是出现的次数 const tagCountMapping = allTags.reduce((res, a) => ((res[a] = (res[a] || 0) + 1), res), {}) 现在它长这样: 3. 排序现在,我们需要通过 mapping 的 value 进行排序,通过 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]); 现在它长这样: 4. 截取前 3 位最终我们得出答案: const res = sortedTag.slice(0, 3) |
function findTheTopThreeElements () { |
@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)
} |
No description provided.
The text was updated successfully, but these errors were encountered: