如何将随机数组值填入表格单列多行?含7个统计表头需求
Got it, let's tackle this problem step by step. We'll create an HTML table with the required headers, generate a random array of numbers, compute all the necessary stats (sorted ascending/descending, max, min, sum, average), then populate everything into the table properly.
Here's the complete, working code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Array Stats Table</title> <style> table { border-collapse: collapse; width: 80%; margin: 20px auto; font-family: Arial, sans-serif; } th, td { border: 1px solid #ddd; padding: 12px; text-align: left; } th { background-color: #f2f2f2; font-weight: bold; } tr:nth-child(even) { background-color: #f9f9f9; } </style> </head> <body> <table id="arrayStatsTable"> <thead> <tr> <th>numbers</th> <th>ascending order</th> <th>descending order</th> <th>max values</th> <th>min values</th> <th>sum of all values</th> <th>avg values</th> </tr> </thead> <tbody> <!-- Content will be populated by JavaScript --> </tbody> </table> <script> // Generate a random array of 5-10 numbers between 1 and 100 const generateRandomArray = () => { const length = Math.floor(Math.random() * 6) + 5; return Array.from({ length }, () => Math.floor(Math.random() * 100) + 1); }; // Compute all required statistics const calculateStats = (arr) => { const ascending = [...arr].sort((a, b) => a - b); const descending = [...arr].sort((a, b) => b - a); const max = Math.max(...arr); const min = Math.min(...arr); const sum = arr.reduce((acc, curr) => acc + curr, 0); const avg = (sum / arr.length).toFixed(2); return { ascending, descending, max, min, sum, avg }; }; // Populate the table const populateTable = () => { const tableBody = document.querySelector('#arrayStatsTable tbody'); const randomArray = generateRandomArray(); const stats = calculateStats(randomArray); // First, add rows for each number in the 'numbers' column randomArray.forEach((num, index) => { const row = document.createElement('tr'); // Numbers column const numCell = document.createElement('td'); numCell.textContent = num; row.appendChild(numCell); // For other columns: only fill the first row with stats, leave others empty if (index === 0) { // Ascending order const ascCell = document.createElement('td'); ascCell.textContent = stats.ascending.join(', '); row.appendChild(ascCell); // Descending order const descCell = document.createElement('td'); descCell.textContent = stats.descending.join(', '); row.appendChild(descCell); // Max value const maxCell = document.createElement('td'); maxCell.textContent = stats.max; row.appendChild(maxCell); // Min value const minCell = document.createElement('td'); minCell.textContent = stats.min; row.appendChild(minCell); // Sum const sumCell = document.createElement('td'); sumCell.textContent = stats.sum; row.appendChild(sumCell); // Average const avgCell = document.createElement('td'); avgCell.textContent = stats.avg; row.appendChild(avgCell); } else { // Add empty cells for remaining rows for (let i = 0; i < 6; i++) { const emptyCell = document.createElement('td'); row.appendChild(emptyCell); } } tableBody.appendChild(row); }); }; // Run the function when the page loads window.onload = populateTable; </script> </body> </html>
Let me break down what this code does:
- Random Array Generation: The
generateRandomArrayfunction creates an array of 5 to 10 random numbers between 1 and 100 (you can adjust the range/length if needed). - Stats Calculation:
calculateStatstakes the array and computes all the required values: sorted ascending/descending arrays, max, min, sum, and average (rounded to 2 decimal places). - Table Population:
- We loop through each number in the random array to create rows for the
numberscolumn. - Only the first row gets filled with all the stats (ascending, descending, max, etc.)—the rest of the rows in those columns stay empty, which makes sense since those stats apply to the entire array, not individual elements.
- We loop through each number in the random array to create rows for the
- Styling: Added basic CSS to make the table clean and readable, with alternating row colors and padded cells.
If you want to adjust the behavior (like showing the sorted arrays in every row, or changing the random number range), just tweak the corresponding parts of the JavaScript. For example, to make the random array longer, change the length calculation in generateRandomArray.
内容的提问来源于stack exchange,提问作者abhinesh ghugloth
相关产品推荐
相关产品推荐

