首页 > 代码库 > Steamroller

Steamroller

function steamroller(arr) {
  // I‘m a steamroller, baby
  //return arr;
  var result = [];
  for(var i = 0; i < arr.length; i++){
    if(Array.isArray(arr[i])){
      result = result.concat(steamroller(arr[i]));
    }else{
      result.push(arr[i]);
    }
  }
  return result;
}

steamroller([1, [2], [3, [[4]]]]);

  或

function steamroller(arr,flatArr) {
  // I‘m a steamroller, baby
  //return arr;
  if (!flatArr)    flatArr = [];

  for (var i in arr) {
    if(!Array.isArray(arr[i])){
      flatArr.push(arr[i]);
    }else {
      steamroller(arr[i],flatArr);
    }
   
  }

  return flatArr;
}

steamroller([1, [2], [3, [[4]]]]);

  

Steamroller