chapter6
My english is poor can’t describe the problem in detail so I paste my practice code:http://jsbin.com/exusox/3/edit
Endless loop when you click the butten.
I’ve tested my code,I found the endless loop in this code:
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;
}
Why this happen and How can I reduce my code?Thanks.
The variable “i” in your “forEach” function is a global variable. You should declare it with
var:Thus when one call to “forEach” involves an action that will itself call “forEach”, the same variable “i” will be reset.
It’s a good idea to put this at the top of your code:
That tells the interpreter to apply some newer rules to the code, and it’d show you an error like that.