标签:正则 func flatten att ons 多维数组 字符串 isa UNC
let ary = [1, [2, [3, [4, 5]]], [6, 7, [8, 9, [11, 12]], 10]]; //=>[1,2,3,4,5,6] let str = JSON.stringify(ary); //=>第一种处理 // console.log(str);//=>[1,[2,[3,[4,5]]],6] // ary = str.replace(/(\[|\])/g, ‘‘).split(‘,‘); //split():用‘,‘来分割,返回一个分割之后的数组 // console.log(ary); //=>第二种处理 str = str.replace(/(\[|\])/g, ‘‘); str = ‘[‘ + str + ‘]‘; ary = JSON.parse(str); console.log(ary);
let result = [], fn = function (ary) { if (ary.length === 0) return; for (let i = 0; i < ary.length; i++) { let item = ary[i]; if (typeof item === ‘object‘) { fn(item); } else { result.push(item); } } }; fn(ary); console.log(result);
let arr = [[1, 2], 3, [[[4], 5]]]; // 数组展平 let fn = function flatten(arr) { return [].concat( ...arr.map(x => Array.isArray(x) ? flatten(x) : x) ) } console.log(fn(arr))
标签:正则 func flatten att ons 多维数组 字符串 isa UNC
原文地址:https://www.cnblogs.com/MrZhujl/p/13174497.html