1. 遍历递归

  1. ~function(){
  2. let myFlat = function() {
  3. let res = [],
  4. _this = this,
  5. fn = arr => {
  6. for(let i = 0;i<arr.length;i++) {
  7. let item = arr[i];
  8. if(Array.isArray(item)) {
  9. fn(item);
  10. continue;
  11. }
  12. res.push(item)
  13. }
  14. }
  15. fn(_this);
  16. return res;
  17. }
  18. Array.prototype.myFlat = myFlat
  19. }()

2.toString

  1. function flatten(arr) {
  2. return arr.toString().split(',')
  3. }

3.reduce

  1. function flatten(arr) {
  2. if(!Array.isArray(arr)) {
  3. throw Error('not array')
  4. }
  5. return arr.reduce((prev,next) => {
  6. return prev.concat(Array.isArray(next)? flatten(next) : next)
  7. },[])
  8. }

4.扩展运算符

  1. function flatten(arr) {
  2. if(!Array.isArray(arr)) {
  3. throw Error('not array')
  4. }
  5. while(arr.some(item => Array.isArray(item))) {
  6. arr = [].concat(...arr)
  7. }
  8. return arr
  9. }

5. Array.prototype.flat

  1. arr.flat(Infinity)