例子:[[0, 1], [2, 3], [4, 5]]转为[0, 1, 2, 3, 4, 5]
转自:https://www.cnblogs.com/EnSnail/p/9762764.html
利用es5
的arr.reduce(callback[, initialValue])
实现
var arr1 = [[0, 1], [2, 3], [4, 5]];
var arr2 = arr1.reduce(function (a, b) { return a.concat(b)} );
// arr2 [0, 1, 2, 3, 4, 5]
利用es6
var arr1 = [[0, 1], [2, 3], [4, 5]];
function flatten(arr) { return [].concat( ...arr.map(x => Array.isArray(x) ? flatten(x) : x) ) }
var arr2 = flatten(arr1); // arr2 [0, 1, 2, 3, 4, 5]
优点: 多维数组也可以
比如:var arr = [[1,2],3,[[[4], 5]]]
利用apply
实现
var arr1 = [[0, 1], [2, 3], [4, 5]];
var arr2 = [].concat.apply([], arr1);
// arr2 [0, 1, 2, 3, 4, 5]
通过将数组转变成字符串,利用str.split(',')
实现。缺点是数组元素都变字符串了
var arr1 = [[0, 1], [2, 3], [4, 5]];
var arr2 = (arr1 + '').split(',');
var arr2 = arr.toString().split(',');
var arr2 = arr.join().split(',');
// arr2 ["0", "1", "2", "3", "4", "5"]
最后补上字符串数组转整型数组的简单方法
var arr2 = ["0", "1", "2", "3", "4", "5"];
var arr3 = arr2.map(Number);
console.log(arr3);//输出为:[0, 1, 2, 3, 4, 5]