Recursive function in javascript

Maybe this is a trivial problem, I do not know why this function exits the loop when it goes further. I need this function to get an XML document.

function xmlToArray(element){
    childs= element.childNodes;
    if(childs.length != 1){
      for(var i=0;i<childs.length;i++){
        if(childs[i].hasChildNodes()){
          xmlToArray(childs[i]);
        }
        alert("exit from if");
      }//end for
      alert("exit from for");
    }//end if
    else{
      alert("do something with element");
    }
    alert("end of func");
}
+3
source share
1 answer

Since it is childsnot a local variable, all calls xmlToArraywork with the same data.

Try the following:

function xmlToArray(element) {
    var childs = element.childNodes;
    // …
}

Usage vardeclares this variable in the current scope.

+8
source

Source: https://habr.com/ru/post/1734588/


All Articles