为了账号安全,请及时绑定邮箱和手机立即绑定

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条经验 获得超7个赞

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


const getConnection = function(cid){

    return allEvents.find(event => {

        return event.connectionId === cid;

    });

}


查看完整回答
反对 回复 2021-11-04
  • 3 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信