题解 | #数组扁平化#
数组扁平化
https://www.nowcoder.com/practice/5d7e0cf4634344c98e6ae4eaa2336bed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
// 最简单可以用ES6的方法flat(Infinity) ,但是好像在这里不支持ES6语法
// 第二种可以用简单的递归思路来完成,
const _flatten = arr => {
// 补全代码
return arr.reduce((per, cur) => {
// 判断当前元素是否数组,是数组则递归,基于递归返回的也是数组,所以多了一处嵌套写法:
// per.push(...[el, el]) => per.push(el, el)
per.push(...(Array.isArray(cur) ? _flatten(cur) : [cur]));
return per
}, [])
};
</script>
</body>
</html>



查看14道真题和解析