【工具方法】页面出现次数最多的标签
williamzhou 4/3/2021  面试编程能力
# 步骤
- 获取页面所有标签
- 哈希表统计计数
- 遍历一趟哈希表,取出最大 tag
# 代码实现
function getFrequentTag () {
  const tags = [].map.call(
    document.querySelectorAll('*'), 
    node => 
      node.tagName.toLowerCase()
  )
  const map = tags.reduce((o, tag) => {
    o[tag] = o[tag] ? o[tag] + 1 : 1
    return o
  }, {})
  const list = Object.entries(map)
  const targetItem = list.reduce((maxTimeItem, item) => {
    return item[1] > maxTimeItem[1] ? item : maxTimeItem
  })
  return targetItem[0]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 测试一下
getFrequentTag()
1
