【问题标题】:Return object from a recursive function that rearranges array of literal objects [closed]从重新排列文字对象数组的递归函数返回对象[关闭]
【发布时间】:2021-12-08 02:19:04
【问题描述】:

我有一个将文字对象作为输入的函数。 作为结果,它应该返回 2 个对象数组。

它是一个递归函数,因此返回发生在第 n 个递归周期,并带有以下数据:

//code
const filterObject = (object, array1 = null, array2 = null) => {
let a1 = array1 === null?[]: array1; //array1 is passed as a part of recursion and when recursed is not null
let a2 = array2 === null?[]: array2; //same here
...
//some filtering and object manipulation to create **composedObject**
...
if (condition x is met){
a1.push(composedObject)
}
if( condition y is met ){
a2.push(composedObject)
...
//filtering out parts of initial object that were used
//what is left is assembled into **untreatedObject**
...
if (there are still parts of the initial object that are left untreated){
 filterObject(untreatedObject, a1, a2); //here recursion happens and we pass these arrays there as well as they will continue to be populated
}
else if (everything is filtered and objects are ready){
console.log(a1) //values are present and correct
console.log(a2) //values are present and correct
 return { a: a1, b: a2};
}

/*
  where

   array1:[
   {
    a: 1,
    b: 'skdfhkdj',
    c:[
     {
       index:0,
       code :'red'
     },
     {
       index:1,
       code :'redcwrg'
     }
    ]
   }
  ],
  
 array2:[
   {
    a: 1,
    b: 'skdfhkdj',
    c:[
     {
       index:2,
       code :'redaxac'
     },
     {
       index:3,
       code :'reddd'
     }
    ]
   }
  ]
*/

const result = filterObject(object, null,null);
console.log(result); //**gives undefined**.   

问题 当我尝试调用此函数 const result = filterObject(object, null,null)(null,null,这里是数组的起始值。它们在函数的开头被分配给 [],然后当递归发生时,它们也被发送,以便新数组可以插入)

当我记录它时,结果是“未定义”类型,我很肯定该函数在 return 发生之前确实有数组中的对象

那么我哪里错了?

提前致谢

【问题讨论】:

  • 什么是filterObject
  • 你应该只问一个问题,否则这会因为太宽泛而被关闭。
  • 你的第二个问题是covered here
  • 注意:在现代 JS 中你可以使用 const a1 = array1 ?? [];
  • 这不是递归调用的返回值。这是基本情况。您的代码不会返回另一个递归案例。所以说清楚,你需要return filterObject(untreatedObject, a1, a2);

标签: javascript node.js asynchronous object-literal


【解决方案1】:

缺少一个导入的东西:您的代码没有返回从递归调用返回的对象。它只有一个return 用于基本情况。您的代码不执行其他递归案例的返回。

所以说清楚,你需要

return filterObject(untreatedObject, a1, a2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多