我正在尝试编写一个调度应用程序,它接收课程信息并创建所有可能的时间表。我以前从未用javascript编写过递归函数,但我不知道为什么它会与任何其他语言不同。
在递归方法中,这些值似乎正确地添加到数组中,但是一旦执行返回到非递归函数,这些值显然会丢失。
下面是有问题的函数(用咖啡脚本编写),这里是我当前功能的一个花招。
请有人告诉我为什么返回的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()发布于 2016-02-16 04:14:23
这是:
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-y方法是使用)。删除日志,如下所示:
if chosenSections.length is Object.keys(courses).length
schedules.push chosenSections...
returnhttps://stackoverflow.com/questions/35423536
复制相似问题