手写loadsh函数的第三天
<script>
const array = [1, [2, [3, [4]], 5]];
function flattenDepth(arr, depth = 1) {
// 验证深度参数是否有效
if (depth < 0) {
alert("很抱歉,你输入的嵌套等级不能小于0");
}
let newArr = arr;
// 根据指定的深度扁平化数组
for (let i = 0; i < depth; i++) {
newArr = [].concat(...newArr);
}
return newArr;
}
// 使用给定的数组和深度测试 flattenDepth 函数
console.log(flattenDepth(array, 2)); // 输出扁平化后的数组
</script>