如何从API返回的JSON数组中选取并显示前10个percent_change_24h值?
I'm fetching an array of 100 items from the CoinMarketCap API. Right now, my code only displays the first item's
percent_change_24hvalue. I want to retrieve and display the first 10 values (indices 0 to 9) to verify the functionality, then calculate their average. Here's my current code:<script> $(document).ready(function () { $.getJSON('https://api.coinmarketcap.com/v1/ticker/', function (data) { document.body.append(data[0].percent_change_24h); }); }); </script>How should I modify this code?
Hey there! Let's break this down into two simple parts: displaying the first 10 values, then calculating their average. Here's how you can adjust your code step by step:
1. Display the first 10 percent_change_24h values
Instead of only accessing the first item with data[0], we'll loop through the first 10 items (indices 0 to 9) using a for loop. We'll also add basic formatting to make the output easier to read:
$(document).ready(function () { $.getJSON('https://api.coinmarketcap.com/v1/ticker/', function (data) { // Create a container to organize our results const resultsContainer = $('<div style="margin: 1rem;"></div>').appendTo('body'); // Loop through the first 10 items for (let i = 0; i < 10; i++) { const change = data[i].percent_change_24h; // Append each value with a label for clarity resultsContainer.append(`#${i+1} 24h Change: ${change}%<br>`); } }); });
2. Calculate the average of these values
To compute the average, we need to convert each string value to a number, sum them up, then divide by the count of valid values (in case some entries don't have a percent_change_24h value):
$(document).ready(function () { $.getJSON('https://api.coinmarketcap.com/v1/ticker/', function (data) { const resultsContainer = $('<div style="margin: 1rem;"></div>').appendTo('body'); let totalChange = 0; let validEntries = 0; for (let i = 0; i < 10; i++) { const change = data[i].percent_change_24h; resultsContainer.append(`#${i+1} 24h Change: ${change}%<br>`); // Skip invalid values to avoid calculation errors if (change !== null && !isNaN(parseFloat(change))) { totalChange += parseFloat(change); validEntries++; } } // Display the average if we have valid data if (validEntries > 0) { const average = (totalChange / validEntries).toFixed(2); // Round to 2 decimal places resultsContainer.append(`<br>📊 Average 24h Change: ${average}%`); } else { resultsContainer.append('<br>No valid 24h change values found for the first 10 items.'); } }); });
Quick notes to keep in mind:
- The API returns
percent_change_24has a string, so we useparseFloat()to convert it to a number for calculations. toFixed(2)ensures the average is rounded to two decimal places for cleaner output.- We added checks for
nulland non-numeric values to prevent crashes if some entries are missing the field.
This code will show each of the first 10 24-hour change values, then display their average at the bottom of the results.
内容的提问来源于stack exchange,提问作者Alb

