慕姐8265434
2021-11-04 15:54:01
我有一個 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 回答

holdtom
TA貢獻1805條經驗 獲得超10個贊
從內部函數返回并不會神奇地從封閉函數返回。您只是從forEach(因為 forEach 返回未定義而沒有意義)返回。forEach在這里也不是正確的選擇,您想要使用的是find
const getConnection = function(cid){
return allEvents.find(event => event.connectionId === cid);
}

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
你不能停止 forEach ... 使用 find 方法。
const getConnection = function(cid){
return allEvents.find(event => event.connectionId == cid);
}

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
getConnection不返回任何東西。find是你需要的:
const getConnection = function(cid){
return allEvents.find(event => {
return event.connectionId === cid;
});
}
添加回答
舉報
0/150
提交
取消