我正在尝试编写一个日程安排应用程序,它接收类(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/