Javascript函数不返回值

时间:2019-09-30 19:37:31

标签: javascript arrays node.js

我有一个JS函数,应该接受一个id作为参数,查找对象数组,然后返回对象。虽然它会打印被调用的对象,但不会返回它。

我尝试将对象分配给变量并返回该变量,这无济于事。

{ "_id" : ObjectId("5ce726ae92e2247db561a2f2"), "requested_completion_utc" : ISODate("2019-05-23T00:00:00Z"), "status_changed_utc" : [ { "status" : 6, "time" : ISODate("2019-05-23T23:05:09Z") } ], "isLate" : true }
{ "_id" : ObjectId("5ce726ae92e2247db561a231"), "requested_completion_utc" : ISODate("2019-09-21T00:00:00Z"), "status_changed_utc" : [ { "status" : 1, "time" : ISODate("2019-09-23T23:03:10Z") } ], "isLate" : true }

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} 打印事件时,console.log(event)返回未定义。

这是呼叫代码:

return event

实际输出应该是事件详细信息。

4 个答案:

答案 0 :(得分:1)

getConnection不返回任何内容。 find是您所需要的:

const getConnection = function(cid){
    return allEvents.find(event => {
        return event.connectionId === cid;
    });
}

答案 1 :(得分:0)

你不能停步... 使用find方法。

const getConnection = function(cid){
 return allEvents.find(event => event.connectionId == cid);
}

答案 2 :(得分:0)

从内部函数返回并不神奇地从封闭函数返回。您只是从forEach返回(这没有意义,因为forEach返回未定义)。 forEach也不是正确的选择,您要使用的是find

const getConnection = function(cid){
    return allEvents.find(event => event.connectionId === cid);
}

答案 3 :(得分:-2)

这是因为在getConnection中您将返回forEach回调。您必须使用find并从 find 方法

返回 found 的值。
const getConnection = function(cid){
    return allEvents.find(event => {
        if(event.connectionId == cid){
           // console.log(event)
            return event
        }
    });
}