获取页面中出现次数最多的三个标签以及出现次数
/**
* @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);