要编写自己的版本Array.prototype.flat(),可以使用递归或迭代的方法来实现。下面是一个使用递归方法的示例代码:
Array.prototype.myFlat = function(depth = 1) {
const result = [];
function flatten(arr, currentDepth) {
arr.forEach(item => {
if (Array.isArray(item) && currentDepth < depth) {
flatten(item, currentDepth + 1);
} else {
result.push(item);
}
});
}
flatten(this, 0);
return result;
};
// 示例用法
const arr = [1, 2, [3, 4, [5, 6]]];
console.log(arr.myFlat()); // [1, 2, 3, 4, [5, 6]]
console.log(arr.myFlat(1)); // [1, 2, 3, 4, [5, 6]]
console.log(arr.myFlat(2)); // [1, 2, 3, 4, 5, 6]
console.log(arr.myFlat(3)); // [1, 2, 3, 4, 5, 6]
在上面的代码中,我们定义了一个新的方法myFlat()
,它接受一个可选的参数depth
来指定要展平的深度,默认为1。我们使用递归方法flatten()
来遍历数组,并将每个元素添加到result
数组中。如果当前元素是数组且深度未达到指定深度,则递归调用flatten()
函数。如果当前元素不是数组或深度已达到指定深度,则将其添加到result
数组中。最后返回result
数组。
你也可以使用迭代的方法来实现,以下是一个使用迭代方法的示例代码:
Array.prototype.myFlat = function(depth = 1) {
let result = [...this];
for (let i = 0; i < depth; i++) {
result = result.reduce((acc, val) => acc.concat(val), []);
}
return result;
};
// 示例用法
const arr = [1, 2, [3, 4, [5, 6]]];
console.log(arr.myFlat()); // [1, 2, 3, 4, [5, 6]]
console.log(arr.myFlat(1)); // [1, 2, 3, 4, [5, 6]]
console.log(arr.myFlat(2)); // [1, 2, 3, 4, 5, 6]
console.log(arr.myFlat(3)); // [1, 2, 3, 4, 5, 6]
在上面的代码中,我们首先将原始数组赋值给result
变量。然后使用reduce()
方法在每个迭代中将数组展平一次,直到达到指定的深度。最后返回result
数组。