developer-plus / interview

https://interview.developer-plus.org
MIT License
9 stars 1 forks source link

如何在 console 中写代码,统计当前页面出现次数最多的三种标签 #25

Open Hongbusi opened 2 years ago

alexzhang1030 commented 2 years ago

先说结论:

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);

现在它长这个样子:

image

2. 统计标签出现的次数

下面我们需要使用 reduce 来进行遍历,根据 mdn 对于 reduce 语法的描述

reduce(callbackFn, initialValue)

我们可以通过构造一个对象来统计,key 是 tagName,value 是出现的次数

const tagCountMapping = allTags.reduce((res, a) => ((res[a] = (res[a] || 0) + 1), res), {})

现在它长这样:

image

3. 排序

现在,我们需要通过 mapping 的 value 进行排序,通过 mdn 对于 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]);

现在它长这样:

image

4. 截取前 3 位

最终我们得出答案:

const res = sortedTag.slice(0, 3)

image

guzao commented 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) }

Hongbusi commented 2 years ago

@guzao 可以看一下 md 语法 - 代码高亮。

likui628 commented 2 years ago

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)
}