如何在保留表格的前提下对JS生成的随机数进行升序排序?
How to Sort Random Numbers in a Table Without Removing the Table Element
Got it, let's tweak your code to fit what you need! Your original setup generates random numbers and renders a table, but it recreates the whole table on page reload and doesn't sort the values. Here's a revised version that keeps the table intact, sorts the numbers correctly, and updates the table content when you click "Odśwież":
<html> <head> <title> Numery losowania </title> <script> // Function to generate, sort, and update the table with random numbers function updateSortedNumbers() { // Create an array to hold 9 random numbers (0-69) const numbers = Array.from({ length: 9 }, () => Math.floor(Math.random() * 70)); // Sort the array numerically (default sort is string-based, so we need a comparator) numbers.sort((a, b) => a - b); // Get the existing table element const table = document.getElementById('numbersTable'); const existingRows = table.querySelectorAll('tr'); // Update or create table rows and cells numbers.forEach((num, index) => { if (existingRows[index]) { // If the row already exists, update its cell content existingRows[index].querySelector('td').textContent = num; } else { // If no row exists, create a new row and cell const row = table.insertRow(); const cell = row.insertCell(); cell.textContent = num; } }); } // Run the function when the page loads to populate the table initially window.addEventListener('load', updateSortedNumbers); </script> </head> <body> <!-- Predefined table element that stays in the DOM permanently --> <table border="1" id="numbersTable"></table> <form> <!-- Button triggers the update function instead of reloading the page --> <input type="button" value="Odśwież" onclick="updateSortedNumbers()"> </form> </body> </html>
Key Changes Explained:
- Persistent Table Element: We added a static
<table>with an ID (numbersTable) in the HTML body. This table stays in the DOM forever—we never delete it, only update its content. - Proper Numerical Sorting: The
numbers.sort((a, b) => a - b)line ensures numbers are sorted correctly. Without this comparator, JavaScript would sort numbers as strings (e.g., 10 would come before 2), which isn't what we want. - Reusable Update Logic:
updateSortedNumbers()handles generating random numbers, sorting them, and updating the table. It checks if rows already exist—if they do, it updates the cell text; if not, it creates new rows. - No Page Reload: The "Odśwież" button now calls our update function instead of reloading the page. This means the table stays visible, and only the numbers change.
内容的提问来源于stack exchange,提问作者Mivalia
相关产品推荐
相关产品推荐

