1

第六章

我的英语很差无法详细描述问题所以我粘贴我的练习代码:http://jsbin.com/exusox/3/edit

单击按钮时无限循环。

我已经测试了我的代码,我在这段代码中发现了无限循环:

function extractFootnotes(paragraphs){
    var footnotes=[],currentNum=0;
    function dealWithFootnote(fragment){
      if(fragment.type=="footnote"){
        currentNum++;
        fragment.number=currentNum;
        footnotes.push(fragment);
        return {type:"reference",number:currentNum};
      }
      else{
        return fragment;
      }
    }
    //run here ,endless loop happened.I've tested forEach,the i++ can't work.
    forEach(paragraphs,function(paragraph){
      paragraph.content=map(dealWithFootnote,paragraph.content);
    });

    return footnotes;
  }


  function forEach(array,action){
    for(i=0;i<array.length;i++)
      action(array[i]);
  }

  function map(func,array){
    var result=[];
    forEach(array,function(element){
      result.push(func(element));
    });
    return result;
  }

为什么会发生这种情况以及如何减少我的代码?谢谢。

我的实践代码

4

1 回答 1

1

“forEach”函数中的变量“i”是一个全局变量。你应该声明它var

function forEach(array, action) {
  var i;
  // ... etc
}

因此,当对“forEach”的调用涉及一个本身将调用“forEach”的操作时,相同的变量“i”将被重置。

将它放在代码的顶部是个好主意:

"use strict";

这告诉解释器对代码应用一些更新的规则,它会向你显示这样的错误。

于 2013-01-23T17:57:58.040 回答