亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript函數不返回值

Javascript函數不返回值

慕姐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);

}


查看完整回答
反對 回復 2021-11-04
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

你不能停止 forEach ... 使用 find 方法。


const getConnection = function(cid){

 return allEvents.find(event => event.connectionId == cid);

}


查看完整回答
反對 回復 2021-11-04
?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

getConnection不返回任何東西。find是你需要的:


const getConnection = function(cid){

    return allEvents.find(event => {

        return event.connectionId === cid;

    });

}


查看完整回答
反對 回復 2021-11-04
  • 3 回答
  • 0 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號