酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

实现一个函数,该函数接受一个数组和一个函数作为参数,返回一个新的数组,新数组中的每个元素是 原数组中对应的元素通过给定的函数处理后的结果。要求使用 array.prototype.reduce 方法来完成 这一操作,而不是直接使用 map 。 输入:一个整数数组 [1, 2, 3] 和一个函数 function(x) { return x * 2; } 输出:一个新的数组 [2, 4, 6]

```javascript function transformArray(arr, func) { return arr.reduce((accumulator, currentValue) => { accumulator.push(func(currentValue)); return accumulator; }, []); } let inputArray = [1, 2, 3]; let transformFunction = function(x) { return x * 2; }; console.log(transformArray(inputArray, transformFunction)); ``` [2024-11-07 15:34:51 | AI写代码神器 | 91点数解答]

相关提问