javascript - 递归 JavaScript 值不回来

标签 javascript recursion coffeescript

我正在尝试编写一个日程安排应用程序,它接收类(class)信息并创建所有可能的日程安排。我以前从未用 javascript 编写过递归函数,但我不确定为什么它与其他语言不同。

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

下面是有问题的函数(用 CoffeeScript 编写),以及 here是对我当前功能的干扰。

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

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()

最佳答案

这个:

schedules.push chosenSections

正在将数组chosenSections通过引用添加到最终数组中。当您稍后使用 chosenSections.pop() 修改此数组时,您期望在 schedules 中的内容实际上会“消失”。您需要将 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

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

更符合 CoffeeScript 风格的方法是使用 splat operator (...) 。删除日志记录,它看起来像这样:

if chosenSections.length is Object.keys(courses).length
    schedules.push chosenSections...
    return

关于javascript - 递归 JavaScript 值不回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423536/

相关文章:

javascript - qTip2 中的 Ajax 表单

java - 在类 Test 中实例化类 Test 的成员是递归吗?

java - 在Java中使用递归编写创建路径的方法

Coffeescript 编译为 Node.js 与浏览器 JS 的区别

javascript - 通过ajax、浏览器弹出窗口提交帖子表单

javascript - 在 mongo 映射或减少上下文中调用外部 javascript 函数(对象)的可能方法

javascript - 缩短 jQuery if else 条件

javascript - 从 Babel 5 迁移到 6 时出错(ReferenceError : exports is not defined)

javascript - 我的 JavaScript 无法运行

java - 硬币变化递归方法