Topic:
var array = [1, [2, 3, [4, 5,], 6], 7, 8];
Write a method Flatarray (array), get [1, 2, 3, 4, 5, 6, 7, 8]
Answer:
1. Two force notation:
function Flatarray (arr) { var temp = arr.join (). Split (', '), = temp.length, = []; for (var i=0; i<len; i++) { Result.push (parseint (Temp[i])); } return result;}
2. Recursion:
functionFlatarray (arr) {varresult = []; for(vari = 0, L = arr.length; I < L; i++){ if(Arr[i]instanceofArray) {Result=Result.concat (Arguments.callee (arr[i)); //or result = Result.concat (Flatarray.call (this, arr[i])); } Else{Result.push (arr[i]); } } returnresult;}
3.forEach (or map, reduce, etc.)
function Flatarray (arr) { var result = []; Arr.foreach (function(item, Index, origin) { ? result = Result.concat (Flatarray ( Item)): Result.push (item); }) return result;}
4. High-end notation (closures):
var function (ret ){function Toarr (arr) { Arr.foreach (function(item) { instanceof Array? Toarr (item): Ret.push (item); }); } return function (arr) { Toarr (arr); return ret; } } ([]);
Interview questions: JavaScript multidimensional array conversion one dimension