共计 1119 个字符,预计需要花费 3 分钟才能阅读完成。
1. Array.prototype.flat()
es6 新增数组办法。Array.prototype.flat()
毛病:须要计算数组的维度
var arr = [1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]
arr.flat(4); // [1,2,21,22,221,2211,2212,3,31,32,33,331,4,{'name': 'jack'}]
应用 Infinity
作为深度,开展任意深度的嵌套数组
var arr = [1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]
arr.flat(Infinity); // [1,2,21,22,221,2211,2212,3,31,32,33,331,4,{'name': 'jack'}]
2. 数组字符串化
毛病:数组内对象无奈转换
var arr = [1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]
arr += '';
arr = arr.split(',');
arr; // [1,2,21,22,221,2211,2212,3,31,32,33,331,4,[object Object]]
3. 递归
var arr = [1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]
function reduceDimension(arr) {let result = [];
let toArr = function(arr) {arr.forEach(function(item) {item instanceof Array ? toArr(item) : result.push(item)
})
}
toArr(arr);
return result;
}
reduceDimension(arr);
4. reduce + concat + 递归
var arr = [1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]
function reduceDimension(arr) {return arr.reduce(function(prev, next){return Array.isArray(next) ? prev.concat(flattenDeep(next)) : prev.concat(next)
}, [])
}
reduceDimension(arr);
正文完