# implements each traversal of a multidimensional array <script type= "Text/javascript" > // var arr=[1,2,3,4,[1,2,3,4]]// arr.foreach (function (Item,index,array)) {} var arr=[12,3,2,3,4,[3,2,4,1],[3,3,1,32,12,4,4,52]] Array.prototype.each=function (FN) { try{// 1, using THIS.I, Records the position of the current traversed element, separate scope this.i | | (this.i=0)// 2, rigorous judgment when to use each ():// when the array length is greater than 0, And the passed argument must be a function if (this.length>0 && fn.constructor==function) {// iterates through the array, using while,for at the bottom, and less for in while ( This.i<this.length) { var e=this[this.i]// determines whether an element is an array if (e & & e.constructor==array) {// Perform a recursive operation if the element is an array e.each (FN) }else{// if the element is non-array, the element is passed to the FN function,// Pass parameters (current element) to FN, and execute function fn fn.call (null,e) } this.i++ }// After the function finishes, free up memory, recycle variables this.i=null } }catch (ex) { //todo handle the exception } return This }&nbsP; console.log (Arr.each ()) </script>
Algorithm-implements each traversal of a multidimensional array (JavaScript)