Given an array that may contain nested arrays, return a flattened array. Input and out put are illustrated as follows. 将含有嵌套的数组转换成扁平化输出。*号部分为需要写出的代码。
var input = [{a: 'a'}, 'b', ['c', 'd'], ['e', ['f']], 'g'];
function flatten_array(arr){
var out = [];
*******;
return out;
}
代码
var input = [{a: 'a'}, 'b', ['c', 'd'], ['e', ['f']], 'g'];
var out = [];
loop(input);
function loop(object) {
for( var a in object ) {
if( typeof(object) === 'object' ) {
loop(object[a]);
}else{
out.push(object[a]);
}
}
}
console.log(out);