在以下代码中,该函数findById()实际上不返回任何内容。在console.log()如预期的火,打印,但结果是该函数被调用时,变量是不确定的。我试图改变返回值类型,甚至只是return true;在没有条件的情况下放在最后,但它总是未定义的。为了确保我没有遗漏一些简单的东西,我实际上创建了一个只返回值的函数istrue()。这实际上工作正常。这是对象/方法定义const database = { // List of authenticated characters characters: [], addCharacter: function(c) { this.characters.push(c); }, findById: function(id) { console.log('Searching for character...'); this.characters.forEach((c) => { if (c.id === id) { console.log('Found'); console.log('cid: ' + c.id); console.log('id: ' + id); return true; // Never actually returns } }); }, istrue: function() { return true; }};以及它被调用的地方const find = database.findById(characterIdToFind);console.log(typeof find); // always undefinedconsole.log(find); // always undefined我希望在我尝试过的这个函数的至少一个排列中会有某种返回值。函数的返回值永远不会有任何变化,只是undefined.
2 回答

HUWWW
TA贡献1874条经验 获得超12个赞
return嵌套函数中的语句从函数返回。
在这种情况下,您可以使用some()而不是forEach()因为您不能打破forEach.
findById: function(id) {
console.log('Searching for character...');
return this.characters.some(c => c.id === id)
}
如果您想获取与使用的给定条件匹配的对象 find()
findById: function(id) {
console.log('Searching for character...');
return this.characters.find(c => c.id === id)
}
如果你在上面的两个方法中看到我们c.id === id在每次迭代中隐式返回,但它不是return从外部函数返回。
添加回答
举报
0/150
提交
取消