You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript函数参数引用问题:map遍历中y值undefined如何解决

Fixing the 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

  1. Incorrect Property Access
    You're using item.param to access the value, but param is a string argument (like "confirmed"). JavaScript interprets item.param as looking for a property literally named param on the item object, not the value stored in the param variable. You need to use bracket notation item[param] instead.

  2. Redundant & Buggy For Loop
    Inside the map callback, you're looping through the entire getCountryInfo array again—this completely overrides the param value on every iteration, and defeats the purpose of using map (which already iterates through each item one by one). This loop is unnecessary and causing incorrect values.

  3. Unnecessary Variable Declarations
    The separate year, month, day declarations 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 Date object 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 map function now correctly returns a new object for each item in getCountryInfo, using the dynamic param argument to fetch the right value for the y property.

内容的提问来源于stack exchange,提问作者RetupK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:37:50