【前端面试】七、算法-数组展平

avatar
作者
猴君
阅读量:0
<!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>Document</title> </head> <body>   <script>     // 判断数组     console.log([].constructor === Array);      console.log( Array.isArray([]));      console.log(Object.prototype.toString.call([]) === '[object Array]');      // 二维数组展平     const flattenOnce = (arr) => {       return [].concat(...arr)     }     const arr1 = [1, [2, 3], [4, 5, 6], [7, 8, 9, 10]];     console.log('flattenOnce',flattenOnce(arr1));      // 多维数组展平     const arr2 = [1, [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, [12, 13, [14, 15]]]];         // 递归     const flatten1 = (arr) => {       return arr.reduce((acc, cur) => {         return acc.concat(Array.isArray(cur) ? flatten1(cur) : cur)       }, [])     }     console.log('flatten1',flatten1(arr2));      // 递归     const flatten2 = (arr) => {       return [].concat(...arr.map(item => Array.isArray(item) ? flatten2(item) : item))     }     console.log('flatten2',flatten2(arr2));      // 生成器     function *flatten3(arr){       for (let i = 0; i < arr.length; i++) {         if(Array.isArray(arr[i])) {           yield *flatten3(arr[i])         } else{           yield arr[i]         }       }     }     console.log('flatten3', [...flatten3(arr2)]);      // 循环     const flatten4 = (arr) => {       while(arr.some(item => Array.isArray(item))) {         arr = [].concat(...arr)       }       return arr     }     console.log('flatten4',flatten4(arr2));      // 栈的思想     const flatten5 = arr => {       let stack = arr.slice()       const r = []        while (stack.length) {         const item = stack.pop()         if(Array.isArray(item)){           stack = stack.concat(item) //stack.push(...item)         } else {           r.unshift(item)         }       }        return r     }     console.log('flatten5',flatten5(arr2));      // 字符串的方法     function flatten6(arr) {       return arr.toString().split(',').map(item => +item)     }     console.log('flatten6',flatten6(arr2));      // 生成器     function *flatten7(arr) {       let stack = arr.slice()        while (stack.length) {         const item = stack.shift()         if(item.constructor === Array) {           stack = stack.concat(item) //stack.push(...item)         } else {          yield item         }       }     }     console.log('flatten7', [...flatten7(arr2)]);    </script>    </body> </html>

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!