Prototypes are provided to us in order for us to extend more versatility.
Today I learned to use JS simulation of the underlying code, the implementation of multidimensional traversal of the array. The idea is to add a method to the array prototype.
1 //JS in the array of the Foreach method, the passing back function can help us to iterate over the array2 varArr =[1,2,3,4,[1,2,[1,4]]];3 Arr.foreach (4 function(item, index, arr) {5alert (item);//1 2 3 4 12146 }7 );8 //we found that this method only gives us the ability to traverse one-dimensional arrays.9 Ten //we want to implement a way to iterate over a multidimensional array and then add a method to the prototype. One //one function of a prototype is to leave us with the properties and methods of the extended object . A //we add an array of each method to traverse a multidimensional array to pass in a return function -Array.prototype.each =function(FN) { - Try{//Core business logic the This. i| | ( This. i = 0);//define a counter if present is original if not present initialized to 0 - //when the array has a length and passes over a function, we execute callbacks on the arrays. - if( This. length>0 && Fn.constructor = =Function) { - while( This. i < This. length) {//to traverse + varE = This[ This. i];//fetch to current element - //if the e element that is taken is an array, then the callback is executed recursively until it is an element + if(e && E.constructor = =Array) { A E.each (FN); at}Else{ - //enter here to explain that the e element is a single element - //we bind the method to the E element, which is equivalent to E calling the FN method - //fn.apply (E,[e]); - Fn.call (e,e); - } in This. i++; - } to } + This. i =NULL;//to remove a reference mark from a garbage collection -}Catch(ex) { the //Do something * } $ };Panax Notoginseng - //call our own method. the Arr.each ( + function(item) { A alert (item); the } +);//1 2 3 4 1 2 1 4 This implements traversing a multidimensional array
JavaScript uses array prototypes to add method implementations to iterate through each element of a multidimensional array