【问题标题】:Recursive JavaScript value not coming back递归 JavaScript 值不会返回
【发布时间】:2025-12-18 14:00:01
【问题描述】:

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

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

以下是有问题的功能(用咖啡脚本编写),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()

【问题讨论】:

  • 什么是@courses?你正在做Object.keys(courses)courses[chosenSections.length],第一个表明courses 是一个对象,但第二个表明它是一个数组。

标签: javascript recursion coffeescript


【解决方案1】:

这个:

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

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

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

【讨论】:

  • 我很抱歉。我的意图是在递归函数的前半部分不返回任何内容,因为我正在修改传入数组的内容。我曾尝试返回变量(因此您指出的错字)但没有任何区别。我已经更新了代码和小提琴以反映这一点。
  • 我明白了。那我再看看吧。
  • 好的,我相信我找到了问题
  • 这很有道理,非常感谢!