我有一个 JS 函数,它应该接受一个 id 作为参数,查找对象数组,然后返回对象。虽然它打印被调用的对象,但它不返回它。我试过将对象分配给一个变量并返回这个变量,这没有帮助。const events = require('../models/events');const allEvents = events.allEvents;const getConnections = function() { return allEvents;}const getConnection = function(cid) { allEvents.forEach(event => { if(event.connectionId == cid) { // console.log(event) return event } });}module.exports = {getConnections, getConnection}whileconsole.log(event)打印事件,return event返回 undefined。这是调用代码:const con = require('./connectionDB')const data = con.getConnection(3)console.log(data)实际输出应该是事件详细信息。
3 回答
![?](http://img1.sycdn.imooc.com/545863080001255902200220-100-100.jpg)
holdtom
TA贡献1805条经验 获得超10个赞
从内部函数返回并不会神奇地从封闭函数返回。您只是从forEach(因为 forEach 返回未定义而没有意义)返回。forEach在这里也不是正确的选择,您想要使用的是find
const getConnection = function(cid){
return allEvents.find(event => event.connectionId === cid);
}
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
繁星淼淼
TA贡献1775条经验 获得超11个赞
你不能停止 forEach ... 使用 find 方法。
const getConnection = function(cid){
return allEvents.find(event => event.connectionId == cid);
}
![?](http://img1.sycdn.imooc.com/5923e28b0001bb7201000100-100-100.jpg)
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
getConnection不返回任何东西。find是你需要的:
const getConnection = function(cid){
return allEvents.find(event => {
return event.connectionId === cid;
});
}
添加回答
举报
0/150
提交
取消