示例
let arr = [1, 2, [3, 4, [5, 6], [7, 8, [9, 10, [11]]]]];
-
使用
toString()-
方法一
const str = arr.toString() // => "1,2,3,4,5,6,7,8,9,10,11" const res = str.split(',').map(Number) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] -
方法二
const str = arr + '' // => "1,2,3,4,5,6,7,8,9,10,11" const res = str.split(',').map(Number) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
相加的过程包含字符串, 会先把数组转换为字符串
-
-
使用
join()
const str = arr.join() // => "1,2,3,4,5,6,7,8,9,10,11"
const res = str.split(',').map(Number) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
-
使用
flat()
const res = arr.flat(infinity) // 默认只转换一级, 输入数字指定转换层级
-
使用正则
const res = JSON.stringify(arr).replace(/(\[|\])/g, ',').split(',').map(Number)