JavaScript函数参数引用问题:map遍历中y值undefined如何解决
y Value in Your Map Function Let's walk through what's causing that undefined and fix your code properly:
Key Issues in Your Current Code
Incorrect Property Access
You're usingitem.paramto access the value, butparamis a string argument (like"confirmed"). JavaScript interpretsitem.paramas looking for a property literally namedparamon theitemobject, not the value stored in theparamvariable. You need to use bracket notationitem[param]instead.Redundant & Buggy For Loop
Inside themapcallback, you're looping through the entiregetCountryInfoarray again—this completely overrides theparamvalue on every iteration, and defeats the purpose of usingmap(which already iterates through each item one by one). This loop is unnecessary and causing incorrect values.Unnecessary Variable Declarations
The separateyear,month,daydeclarations are redundant since you're destructuring the date split directly into them.
Corrected Code
let confirmed = {}; let deaths = {}; let recovered = {}; // Rewrite the function to fix the logic const objectWithParams = (param) => { return getCountryInfo.map((item) => { // Parse the date string directly into a Date object const [year, month, day] = item.date.split("-").map(Number); const date = new Date(year, month - 1, day); // Note: months are 0-indexed in JS Date! // Use bracket notation to access the dynamic property return { x: date, y: item[param] }; }); }; confirmed = objectWithParams('confirmed'); console.log(confirmed);
Additional Notes
- Don't forget that JavaScript's
Dateobject uses 0-indexed months (January = 0, December = 11), so we subtract 1 from the parsed month value to get the correct date. - I restructured the function to make it more readable—you can keep it as an arrow function without curly braces if you prefer, but splitting it into lines helps with clarity.
- The
mapfunction now correctly returns a new object for each item ingetCountryInfo, using the dynamicparamargument to fetch the right value for theyproperty.
内容的提问来源于stack exchange,提问作者RetupK

