JS20. 数组扁平化
描述
请补全JavaScript代码,要求将数组参数中的多维数组扩展为一维数组并返回该数组。示例1
输入:
[1,[2,[3,[4]]]]
输出:
[1,2,3,4]
HTML/CSS/JavaScript 解法, 执行用时: 1684ms, 内存消耗: 77772KB, 提交时间: 2022-02-09
{"css":"","js":"","html":"<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n \n <script>\n let res = []\n const _flatten = arr => {\n // 补全代码\n \n arr.forEach(item=>{\n if(Array.isArray(item)){\n _flatten(item)\n }else{\n res.push(item)\n }\n })\n return res\n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1685ms, 内存消耗: 77808KB, 提交时间: 2022-02-08
{"css":"","js":"","html":"<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n \n <script>\n const _flatten = arr => {\n // 补全代码\n return Array.isArray(arr) \n ? arr.reduce((l, e) => l.concat(_flatten(e)), [])\n : arr;\n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1734ms, 内存消耗: 77796KB, 提交时间: 2022-01-27
{"css":"","js":"","html":"<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n \n <script>\n const _flatten = arr => {\n // 补全代码\n const result = []\n const flattenArr = arr => {\n for (let item of arr) {\n if (item instanceof Array) {\n flattenArr(item)\n } else {\n result.push(item)\n }\n }\n }\n \n flattenArr(arr)\n return result\n \n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1739ms, 内存消耗: 77772KB, 提交时间: 2021-12-05
{"css":"","js":"","html":"<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n \n <script>\n const _flatten = arr => {\n // 补全代码\n return arr.reduce((a, item)=>{\n if(Array.isArray(item)){\n return a.concat(_flatten(item))\n }else{\n return a.concat(item)\n }\n }, [])\n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1741ms, 内存消耗: 77772KB, 提交时间: 2021-12-07
{"css":"","js":"","html":"<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n \n <script>\n const _flatten = arr => {\n // 补全代码\n var res=[]\n for(var i=0;i<arr.length;i++){\n if((typeof arr[i])!='number'){\n arr=arr[i];\n i=-1;\n }else{\n res.push(arr[i])\n }\n }\n return res\n }\n </script>\n </body>\n</html>","libs":[]}