如何使用unshift()简便向数组添加数字并生成倒序年份数组?
Hey there! I get that you want a cleaner way to generate that descending year array using unshift() instead of your current approach with push() and reverse(). Let's break this down and simplify your code step by step.
The Problem with Your Current Approach
Your existing code works, but it takes an extra step to build the array in ascending order first, then reverse it. We can cut out that reverse step entirely by leveraging unshift() to build the array in descending order directly.
Using unshift() to Build the Array Directly
Since unshift() adds elements to the beginning of an array, we can loop from your favorite singer's debut year (1999) up to the current year, and each time add the year to the start of the array. This automatically gives us the descending order we want without needing to reverse later.
Here's the simplified, cleaner code:
// Define fixed debut year and get current year dynamically const debutYear = 1999; const currentYear = new Date().getFullYear(); const years = []; // Loop from debut year to current year, adding each to the start of the array for (let year = debutYear; year <= currentYear; year++) { years.unshift(year); } // Generate list items concisely with map() const yearListItems = years.map(year => `<li><a href="${year}.html">${year}</a></li>` ).join(''); // Add the list to the DOM (safer than document.write) document.body.insertAdjacentHTML('beforeend', yearListItems);
What's Happening Here?
- We start by defining clear variables for
debutYear(easy to update if needed) andcurrentYear(grabbed dynamically so it stays accurate every year). - The loop runs from 1999 up to the current year. Each
unshift(year)adds the year to the front of the array—by the end, we have[2018, 2017, ..., 1999](or whatever the current year is). - Instead of a clunky
whileloop for output, we usemap()to convert each year into an HTML list item string, thenjoin()them all into a single string. This is far more readable. - We use
insertAdjacentHTML()instead ofdocument.write()—it's a better practice becausedocument.writecan overwrite your entire page if called after the page finishes loading.
Bonus: Alternative Without unshift()
If you're open to another concise approach, you can loop downward from the current year to 1999 and use push(), which is slightly more performant (adding to the end of an array is faster than the beginning):
const debutYear = 1999; const currentYear = new Date().getFullYear(); const years = []; for (let year = currentYear; year >= debutYear; year--) { years.push(year); } // Same output code as above const yearListItems = years.map(year => `<li><a href="${year}.html">${year}</a></li>` ).join(''); document.body.insertAdjacentHTML('beforeend', yearListItems);
Either method will give you the clean, descending array you want without the verbose code you had before!
内容的提问来源于stack exchange,提问作者SongD

