数组的扁平化,是将一个嵌套多层的数组 array (嵌套可以是任何层数)转换为只有一层的数组

    1. function flatten1(arr) {
    2. return arr.join(',').split(',').map(function(item) {
    3. return Number(item);
    4. })
    5. }
    6. function flatten2(arr) {
    7. var newArr = [];
    8. arr.map(item => {
    9. if(Array.isArray(item)){
    10. newArr.push(...flatten2(item))
    11. } else {
    12. newArr.push(item)
    13. }
    14. })
    15. return newArr
    16. }
    17. function flatten3(arr) {
    18. let stack = [...arr].reverse()
    19. let newArr = []
    20. while(stack.length){
    21. let o = stack.pop()
    22. if(Array.isArray(o)){
    23. stack.push(...o.reverse())
    24. } else {
    25. newArr.push(o)
    26. }
    27. }
    28. return newArr
    29. }
    30. function flatten4(arr) {
    31. while(arr.some(item=>Array.isArray(item))) {
    32. arr = [].concat(...arr);
    33. }
    34. return arr;
    35. }
    36. flatten1([3,[4,8,[9,1],3],[6,8],[2,10],5,7])
    37. flatten2([3,[4,8,[9,1],3],[6,8],[2,10],5,7])
    38. flatten3([3,[4,8,[9,1],3],[6,8],[2,10],5,7])
    39. flatten4([3,[4,8,[9,1],3],[6,8],[2,10],5,7])