首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归JavaScript值不返回

问递归JavaScript值不返回
EN

Stack Overflow用户
提问于 2016-02-16 04:06:55
回答 1查看 74关注 0票数 1

我正在尝试编写一个调度应用程序,它接收课程信息并创建所有可能的时间表。我以前从未用javascript编写过递归函数,但我不知道为什么它会与任何其他语言不同。

在递归方法中,这些值似乎正确地添加到数组中,但是一旦执行返回到非递归函数,这些值显然会丢失。

下面是有问题的函数(用咖啡脚本编写),这里是我当前功能的一个花招。

请有人告诉我为什么返回的schedules中的两个数组都是空的?

代码语言:javascript
复制
combine: ->
    schedules = []
    @recursiveCombine(@courses, [], schedules)
    return schedules

recursiveCombine: (courses, chosenSections, schedules) ->
    if chosenSections.length is Object.keys(courses).length
        console.log 'pushing schedule: '
        for section in chosenSections
            console.log '\t' + section.courseName + ' ' + section.number

        schedules.push chosenSections
        return

    next = chosenSections.length
    course = courses[next]
    for section in course.sections
        if not @overlap(section, chosenSections)
            chosenSections.push section
            @recursiveCombine(courses, chosenSections, schedules)
            chosenSections.pop()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-16 04:14:23

这是:

代码语言:javascript
复制
schedules.push chosenSections

是通过引用最后一个数组来添加数组chosenSections。当您稍后用chosenSections.pop()修改这个数组时,您期望在schedules中出现的东西就会有效地“消失”。您需要将chosenSections数组复制到schedules中。从代码的其余部分来看,您可能只是想将其扁平化:

代码语言:javascript
复制
if chosenSections.length is Object.keys(courses).length
    console.log 'pushing schedule: '
    for section in chosenSections
        console.log '\t' + section.courseName + ' ' + section.number

        #here we are copying a reference to each item inside chosenSections
        schedules.push section
    return

一个更多的CoffeeScript-y方法是使用)。删除日志,如下所示:

代码语言:javascript
复制
if chosenSections.length is Object.keys(courses).length
    schedules.push chosenSections...
    return
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35423536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档