gpt4 book ai didi

javascript - js递归函数未返回正确的子对象

转载 作者:行者123 更新时间:2023-12-03 09:48:39 24 4
gpt4 key购买 nike

我正在尝试编写一个递归函数,它根据索引数组返回模型中正确的嵌套对象。

我的控制台日志标记为“内部函数”实际上显示了正确的对象!这让我感到困惑,因为我之后所做的就是返回该 obj,但该函数似乎再次运行并返回父级。

JSFiddle

var model = [
{ name: 'Item 1' },
{
name: 'Item 2',
sub: [
{ name: 'Item 2.1' },
{ name: 'Item 2.2' },
{ name: 'Item 2.3' }
]
},
{ name: 'Item 3' },
{ name: 'Item 4' }
];

function getObj(collection, array) {
var data = collection[array[0]];
if(array.length > 1) {
array.shift();
arguments.callee(data.sub, array);
}
console.log('inside function', data);
return data;
}

var obj = getObj(model, [1, 2]); // expecting obj.name === 'Item 2.3'
console.log('result', obj); // obj.name === 'Item 2'

最佳答案

当你递归时

arguments.callee(data.sub, array);

您没有返回结果,而是忽略结果并返回初始调用中的数据。

尝试向该行添加一个return,以便递归调用的结果是整个函数的结果。

另请注意 arguments.callee在严格模式下不起作用。

Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.

要在严格模式下工作,你可以这样做

return getObj(data.sub, array);

关于javascript - js递归函数未返回正确的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30941552/

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