从循环函数返回值

编程入门 行业动态 更新时间:2024-10-13 08:19:09
本文介绍了从循环函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这个 Meteor 服务器递归方法 commonHint 返回 result undefined 到控制台,即使 finalRes 有一个值.关于如何将 finalRes 返回给调用者的任何建议?谢谢

This Meteor server recursive method commonHint returns result undefined to the console even the finalRes has a value. Any suggestion on how to return the finalRes to the caller? thx

//call the recursive method let result = thismonHint(myCollection.findOne({age: 44}), shortMatches); console.log('got most common hint: ' + result); // <=== undefined ==== 'commonHint': function (doc, shortMatches, hinters, results = []) { // first call only first 2 args are defined, if (!hinters) { hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)]; thismonHint(doc, shortMatches, hinters, results); // hinters is an array of length 3 with 2 elements each return; } // get an element from hinters, use its 2 hinters and remove that element from the hinters let hintersToUse = hinters.pop(); let hinter1 = this.cleanMatchItem(hintersToUse[0]); let hinter2 = this.cleanMatchItem(hintersToUse[1]); let intersect = _.intersection(hinter1, hinter2); // which item of the shortMatches best matches with the intersect let tempCol = new Meteor.Collection(); for (let i = 0; i < shortMatches.length; i++) { tempCol.insert({match: shortMatches[i]}); } results.push(mostSimilarString(tempCol.find({}), 'match', intersect.join(' '))); if (hinters.length > 0) { thismonHint(doc, shortMatches, hinters, results); } else { let finalRes = lib.mostCommon(results); console.log(finalRes); //<==== has a value return finalRes; //<==== so return it to caller } },

推荐答案

递归函数中返回结果的每个路径必须返回一个结果.在您的路径中,您有不提供的路径:当未提供 hinters 时,以及当 hinters.length >0 为真.

Every path out of a recursive function that returns a result must return a result. In yours, you have paths that don't: When hinters isn't provided, and when hinters.length > 0 is true.

你应该返回递归调用的结果:

You should return the result of the recursive call:

if (!hinters) { hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)]; return thismonHint(doc, shortMatches, hinters, results); // hinters is an array of length 3 with 2 elements each // ^^^^^^ } // ... if (hinters.length > 0) { return thismonHint(doc, shortMatches, hinters, results); // ^^^^^^ } else { let finalRes = lib.mostCommon(results); console.log(finalRes); //<==== has a value return finalRes; //<==== so return it to caller }

更多推荐

从循环函数返回值

本文发布于:2023-11-26 02:29:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!