gpt4 book ai didi

javascript - 递归函数如何将消息保存在数组中?

转载 作者:行者123 更新时间:2023-12-01 01:04:25 25 4
gpt4 key购买 nike

我创建了递归函数,可以对嵌套对象进行排序,并根据某些属性从中获取消息。最后我想获得一个包含消息的数组,但是当函数迭代自身时,它会重写旧的数组。如何在不丢失以前的消息的情况下继续将消息推送到数组并返回该数组

我尝试在 jsfidle 中重现我的代码,但我的递归函数只运行一次。无论如何,如果您需要我正在使用的对象,这里有一个链接 https://jsfiddle.net/armakarma/hvj62una/1/

  getMessageFromStage(data, algoritmID, stageIDS) {
let stage = data[algoritmID][stageIDS]
let result = []
let nextStageId = null
let nextAlgId = null

// here i'm pushing messages to result array

if (stage.messages.length) {
for (let i = 0; i < stage.messages.length; i++) {
if (stage.messages[i].message_type === "text") {
result.push(stage.messages[i].message)
}
}
}
if (stage.render === true) {
nextStageId = stage.stageID
} else {
nextStageId = 1
}
if (stage.algoritm_id) {
nextAlgId = stage.algoritm_id
} else {
nextAlgId = algoritmID
}

if (nextStageId && nextAlgId && stage.render) {
this.getMessageFromStage(data, nextAlgId, nextStageId)
}
}

最佳答案

至少有两个解决方案。

  1. 创建一个外部函数,声明结果并首次调用getMessageFromStage
myFun(data, algoritmID, stageIDS) {
const results = [];
this.getMessageFromStage(data, algoritmID, stageIDS);
return results;
}
  • results作为getMessageFromStage的另一个可选参数,并将其与每个递归调用一起传递。
  • getMessageFromStage(data, algoritmID, stageIDS, results = []) {
    //...
    if (nextStageId && nextAlgId && stage.render) {
    this.getMessageFromStage(data, nextAlgId, nextStageId, results);
    }
    }

    关于javascript - 递归函数如何将消息保存在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55774328/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com