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

函数返回undefined求助:为员工对象添加销售数据失败

问题原因与修复方案

核心问题:函数未返回map执行结果

你调用函数得到undefined的根本原因是:mapEmpAndSales函数内部执行了employeesData.map(),但没有将map返回的新数组作为函数结果返回。JavaScript中,函数如果没有显式return语句,默认返回undefined,这就是你调用后得到该结果的原因。

而函数内部console.log能显示正确数据,是因为map的迭代逻辑本身是正确的,每个循环里都生成了带sales字段的员工对象,但这些对象组成的数组没有被传递到函数外部。

修复代码

只需给函数添加return语句,将map的执行结果返回即可:

function mapEmpAndSales() {
    // 把map生成的新数组作为函数返回值
    return employeesData.map(function(employee) {
        let newEmpInfo = Object.assign({}, employee);
        newEmpInfo.sales = salesData.filter(function(element) {
            return element.staffId == employee.id;
        });
        return newEmpInfo;
    });
}

可选:如果只需要单个员工的结果

如果你的预期是返回示例中id=3的单个员工对象,可以在map之后添加find方法筛选:

function mapEmpAndSales() {
    return employeesData.map(function(employee) {
        let newEmpInfo = Object.assign({}, employee);
        newEmpInfo.sales = salesData.filter(function(element) {
            return element.staffId == employee.id;
        });
        return newEmpInfo;
    }).find(emp => emp.id === 3);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:25:51