JavaScript函数getYearFromObjectArray报错排查与功能实现需求问询
First, let's break down the issues with your original code and fix them to meet your new requirement.
Why the Original Error Happened
You called getYearFromObjectArray(dumpObjectArray) before assigning a value to dumpObjectArray. Even though var hoists variable declarations, the actual data assignment happens later. So when the function ran, dumpObjectArray was still undefined, causing the error when trying to use .filter() on it. Additionally, your function was checking for a non-existent key property in the objects, which wasn't aligned with your data structure.
Corrected Solution Code
Here's the revised code that fixes the error and returns the exact values you need for your D3 scatter plot:
// Define the data array first so it's available when the function runs var dumpObjectArray = [ { 2000: "3861703.86265837", 2001: "3948395.50088809", 2002: "4079614.75274644", 2003: "4243914.23578233", 2004: "4473182.3714518", 2005: "4666976.64129297", 2006: "4912930.11306349", 2007: "5230542.3962404", 2008: "5447541.9024238", 2009: "5614275.08094141", 2010: "5873859.25045115" }, { 2000: "6445883.82450361", 2001: "6500776.94950847", 2002: "6510827.66224668", 2003: "6702943.57911293", 2004: "6732003.46639188", 2005: "6712282.82564533", 2006: "6846499.23063543", 2007: "6837383.17387017", 2008: "6810185.26824634", 2009: "6283177.01076618", 2010: "6544487.27529572" } ]; function getYearFromObjectArray(year) { // Convert input year to string (object keys are stored as strings internally) const yearKey = String(year); // Extract the value for the target year from each object in the array return dumpObjectArray.map(obj => obj[yearKey]); } // Example usage: console.log(getYearFromObjectArray(2007)); // Output: ["5230542.3962404","6837383.17387017"] console.log(getYearFromObjectArray("2007")); // Same output as above
Key Improvements Explained
- Fixed Variable Scope: We moved the
dumpObjectArraydefinition above the function call, ensuring it's fully initialized when the function runs. - Rewrote Function Logic:
- Replaced
.filter()with.map()to directly extract values instead of filtering objects (your original logic was looking for akeyproperty that doesn't exist in your data). - Added
String(year)to handle both numeric and string year inputs, since object keys are always stored as strings.
- Replaced
- Meets Your Exact Requirement: Calling the function with either
2007or"2007"returns the array of values you need for your scatter plot.
This implementation will integrate smoothly with your D3 workflow, providing the data points you need to visualize selected year CO2 values.
内容的提问来源于stack exchange,提问作者Samson Kemba

