为什么这个js函数返回未定义的对象



所以我有两个JS函数,loadReport正在调用getCurrentReport。在返回之前,我已经检查了我是否有正确的对象,但是调用者没有收到那个对象。为什么?

getCurrentReport(id) {
this.reports.forEach(e => {
if (e.id === id) {
console.log(e);     // This prints exactly the object that I want
return e;    // So I assume I should get this object..
}
});
}
async loadReport(id) {
var report = this.getCurrentReport(id);
console.log("Getting:");
console.log(report);    // And yet I'm getting undefined here?
},

有人能给我解释一下吗?

getCurrentReport没有返回任何内容,因此report将是undefined

我假设您正在使用forEach来尝试"查找"报告,如果是这样,您应该使用Array的find函数

getCurrentReport(id) {
return this.reports.find(e => e.id === id);
}

您在forEach中返回e。尝试在forEach外部声明一个变量,并将e分配给它,然后将其返回到forEach 外部

参考以下

function getCurrentReport(id) {
//declare a variable to hold e
let currentReport;
//sample arrray taken
[{id:1,name:"abc"}, {id:2,name:"xyz"}].forEach(e => {
if (e.id === id) {
console.log(e);     // This prints exactly the object that I want
currentReport = e;    // So I assume I should get this object..
}
});

//return here
return currentReport
}
async function loadReport(id) {
var report = getCurrentReport(id);
console.log("Getting:");
console.log(report);    // And yet I'm getting undefined here?
}

setTimeout(() => {
loadReport(1)
}, 1000);

最新更新