# ES6+ flat()

## 2. ES5 中的处理方法

ES5 中没有类似的方法，如果要达到目标结果需要自己写函数针对性处理。

``````function flat(arr){
if(Object.prototype.toString.call(arr) != "[object Array]"){return false};
let res = [];
for(var i=0;i<arr.length;i++){
if(arr[i] instanceof Array){
res = res.concat(flat(arr[i]))
}else{
res.push(arr[i])
}
}
return res;
};
var arr = [1,2,[3,4,5,[6,7,8],9],10,[11,12]];
flat(arr);	// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
``````

## 3. 方法详情

### 3.1 语法使用

``````var newArray = arr.flat([depth])
``````

depth 指定要提取嵌套数组结构的深度，默认值为 1

### 3.2 语法示例

``````var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();      // [1, 2, 3, 4, [5, 6]]
arr.flat(2);     // [1, 2, 3, 4, 5, 6]
``````

``````var arr = [1, 2, [3, 4, [5, 6, [7, 8]]]];
arr.flat(Infinity);  // [1, 2, 3, 4, 5, 6, 7, 8]
``````

### 3.3 数组空项

``````var arr = [1, 2, , 4, 5];
arr.flat();      // [1, 2, 4, 5]
``````

## 4. 案例：深拷贝数组

``````var arr1 = [1, 2, [3, 4, [5, 6]]];
var arr2 = arr1.flat(0);
arr2.push(100)
console.log(arr1)		// [1, 2, [3, 4, [5, 6]]]
console.log(arr2)		// [1, 2, [3, 4, [5, 6]], 100]
``````