要实现这个功能,我们可以通过 `Array.prototype.reduce` 方法来构建新的数组。`reduce` 方法接收一个累加器(accumulator)和当前值(current value),并返回一个新的累积值。在这个例子中,我们可以将累加器初始化为一个空数组,然后在每次迭代时,将处理后的元素添加到累加器数组中。 下面是具体的实现代码: ```javascript function transformArray(arr, transformer) { return arr.reduce(function(accumulator, currentValue) { // 使用提供的函数处理当前值 const transformedValue = transformer(currentValue); // 将处理后的值添加到累加器数组中 accumulator.push(transformedValue); // 返回更新后的累加器 return accumulator; }, []); // 累加器初始值为空数组 } // 测试函数 const inputArray = [1, 2, 3]; const transformFunction = function(x) { return x * 2; }; const resultArray = transformArray(inputArray, transformFunction); console.log(resultArray); // 输出: [2, 4, 6] ``` 在这段代码中: - `transformArray` 函数接收两个参数:一个数组 `arr` 和一个转换函数 `transformer`。 - `reduce` 方法用于遍历数组 `arr` 的每个元素,并且使用 `transformer` 函数处理这些元素。 - 在每次迭代中,`transformedValue` 存储了经过 `transformer` 处理后的元素值。 - 这个值被添加到 `accumulator` 数组中,`accumulator` 是一个在每次调用 `reduce` 回调时传递的数组。 - 最终,`reduce` 返回的是包含所有处理后元素的新数组。 这种方式不仅实现了类似 `map` 的功能,而且通过 `reduce` 来构建数组,展示了如何利用不同的数组方法来解决问题。 [2024-11-12 08:20:00 | AI写代码神器 | 402点数解答]