首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我在这个递归JavaScript函数中做错了什么?

我在这个递归JavaScript函数中做错了什么?
EN

Stack Overflow用户
提问于 2011-02-21 02:04:27
回答 2查看 741关注 0票数 0

下面是整个页面:

代码语言:javascript
复制
<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如下所示:

代码语言:javascript
复制
[
   {
      "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如下所示:

代码语言:javascript
复制
[
   {
      "id":"16607",
      "mtype":"entry",
      "label":"News, links and random thoughts"
   },
   {
      "id":"16607",
      "mtype":"entry",
      "label":"News, links and random thoughts"
   }
]

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-21 02:27:18

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

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

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

代码语言:javascript
复制
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;
}
票数 4
EN

Stack Overflow用户

发布于 2011-02-21 02:23:08

似乎index被声明为全局变量,并且在每次调用buildList时都会发生变化。我认为这就是你的问题(但也许你是故意这么做的,而我没有注意到)。尝试将for语句更改为:

代码语言:javascript
复制
for(var index=0; index < lis.length; index++){
    // ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5058889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档