gpt4 book ai didi

javascript - 我对这个递归 JavaScript 函数做错了什么?

转载 作者:行者123 更新时间:2023-11-28 14:01:14 27 4
gpt4 key购买 nike

这是整个页面:

<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
<script type="text/javascript" src="/json2.js"></script>
<script type="text/javascript">
function buildList(point) {
if ( !point )
return [];
children = [];
lis = point.children('li');
for (index = 0; index < lis.length; index++) {
id = $(lis[index]).attr('id');
parts = id.split('-');
title = $(lis[index]).children('div').text();
newObj = {
id: parts[1],
mtype: parts[0],
label: title
}
ol = $(lis[index]).children('ol');
// if (ol.length == 1) {
// newObj['childobjects'] = buildList(ol);
// }
children.push(jQuery.extend(true, {}, newObj));
}
return children;
}
$(function() {
obj = buildList( $('#menu-top') );
alert( JSON.stringify(obj) );
});
</script>
</head>
<body>
<ol id="menu-top" class="sortable ui-sortable">
<li id="entry-16608">
<div>Test item 1</div>
<ol>
<li id="entry-16607" ">
<div>News, links and random thoughts</div>
</li>
</ol>
</li>
<li id="entry-16609">
<div>How a data retention mandate will likely lead to de facto censorship in the US</div>
</li>
<li id="entry-16579">
<div>Git cheat sheet</div>
</li>
</ol>
</body>
</html>

当我注释掉递归调用时,我的 JSON 如下所示:

[
{
"id":"16608",
"mtype":"entry",
"label":"Test item 1"
},
{
"id":"16609",
"mtype":"entry",
"label":"How a data retention mandate will likely lead to de facto censorship in the US"
},
{
"id":"16579",
"mtype":"entry",
"label":"Git cheat sheet"
}
]

当我取消注释代码时,JSON 如下所示:

[
{
"id":"16607",
"mtype":"entry",
"label":"News, links and random thoughts"
},
{
"id":"16607",
"mtype":"entry",
"label":"News, links and random thoughts"
}
]

我猜这是因为我对 JavaScript 如何处理作用域和递归的细节一无所知,但我不知道在这里该怎么做。

最佳答案

是的,这是一个范围问题。您忘记将 var 放在 all 变量前面。这使得变量成为全局变量,这意味着每个函数调用都可以访问相同的变量(并覆盖它们)。

查看修复版本:http://jsfiddle.net/fkling/uYXYh/

您可以通过使用更多 jQuery 方法来进一步改进代码:

function buildList(point) {
if (!point) return [];
var children = [];
point.children('li').each(function() {
var parts = this.id.split('-');
var newObj = {
id: parts[1],
mtype: parts[0],
label: $(this).children('div').text()
};
var $ol = $(this).children('ol');
if ($ol.length == 1) {
newObj['childobjects'] = buildList($ol);
}
children.push(jQuery.extend(true, {}, newObj)); // not sure why you are
// doing this instead of
// children.push(newObj)
});
return children;
}

DEMO

关于javascript - 我对这个递归 JavaScript 函数做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5058889/

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