我有一个函数,它接受一个文字对象作为输入。作为结果,它应该返回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这里是数组的起始值。它们在函数开始时被赋值给[],然后当递归发生时,它们也被发送,以便可以替换新数组)
,当我记录它时,结果类型为&;undefined&;并且我确信函数在return
发生之前确实有数组中的对象
那么我哪里错了呢?
Thanks in advance
缺少一件重要的事情:您的代码没有返回递归调用返回的对象。它只有基本情况下的return
。您的代码不执行其他递归情况的返回。
为了更清楚,你需要
return filterObject(untreatedObject, a1, a2);