码迷,mamicode.com
首页 > 其他好文 > 详细

获取页面中出现次数最多的三个标签以及出现次数

时间:2018-03-01 17:13:30      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:fun   dom   i++   res   sort   case   get   let   com   

/**
* @method getDomCounts - Get the tag information in some page;
* @param
* @return An object with the result of tag name as key and tag counts for value.
*/
function getDomCounts() {
let nodes = document.getElementsByTagName(‘*‘);
let tags = {};
for (let i = nodes.length - 1; i; i--) {
var tagName = nodes[i].tagName.toLowerCase();
if (tags[tagName]) {
tags[tagName]++;
} else {
tags[tagName] = 1;
}
}
return tags;
}
/**
* @method sortTags - sort an object by value of an object;
* @param tagsInfo - an object which needs to be sorted;
* @return An Array composed by the object key
*/

function sortTags(tagsInfo) {
return Object.keys(tagsInfo).sort((a,b)=> {
return tagsInfo[b]-tagsInfo[a]
})
}
let tagsInfo = getDomCounts();
let sortedTags = sortTags(tagsInfo);
let mostUsedTags= {};
for (let i = 0; i < 3; i++) {
let key = sortedTags[i];
mostUsedTags[key] = tagsInfo[key]
}
console.log(mostUsedTags);

获取页面中出现次数最多的三个标签以及出现次数

标签:fun   dom   i++   res   sort   case   get   let   com   

原文地址:https://www.cnblogs.com/drop-in-ocean/p/8488345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!