Make writing a habit together! This is the 9th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

c

⭐ ⭐

2. What is the meaning of this passage?

  • DOM API proficiency
  • Pseudo-array to array
  • Array to heavy

If you look at the problem and you don’t have any ideas, you can refer to the above knowledge point and think about how to solve it.

A:

new Set([...document.getElementsByTagName(The '*')].map(v= > v.tagName)).size
Copy the code

Put this code to the nuggets front page for a test:

I looked at the answer and found that it was no more than that, but if you were suddenly thrown a question like this, you might not be able to write it out immediately.

Make it harder:

Open a webpage randomly, count the three kinds of labels and the frequency of occurrence in the page.

On the basis of the previous question, it is also considered that:

  • Count the number of occurrences of each element in the array
  • Sort by an item in the array
  • Object.entries

A:

const arr = [...document.getElementsByTagName("*")].map(tag= >tag.tagName)
const obj = arr.reduce((pre, i) = >{
  pre[i] = (pre[i] || 0) + 1;
  return pre;
}, {})
const res = Object.entries(obj).sort((a, b) = >(b[1] - a[1])).slice(0.3)
console.table(res)
Copy the code

Of course, the above notation uses the Object.entries API, but if you do not use object. entries, it is ok to write it differently, such as using a new Object to count the three most used tags:

const arr = [...document.getElementsByTagName("*")].map(tag= >tag.tagName)
const obj = arr.reduce((pre, i) = >{
  pre[i] = (pre[i] || 0) + 1;
  return pre;
}, {})

const countArr = Object.keys(obj).sort((a,b) = > obj[b] - obj[a])
const res = {}
countArr.slice(0.3).forEach(v= > {
  res[v] = obj[v]
})
console.log(res)
Copy the code

At the end

This topic is not difficult at all, is to see the usual business code written proficient, if the usual writing is to check an API step, it may be tested.

Alin level is limited, the article if there are mistakes or improper expression of the place, very welcome to point out in the comment area, thanks ~

If my article is helpful to you, your 👍 is my biggest support ^_^

You can also follow the front End Daily Question column in case you lose contact

I’m Allyn, export insight technology, goodbye!

The last:

“Front-end Daily Question (45)” What are variable promotions and temporary dead zones?

Next up:

The “Front End of the Day question (47)” talks about MEMORY management of JS, and gives some examples of memory leaks.