请编写一个函数,模仿
Array
对象的map()
方法,接受一个数组和一个函数作为参数,返回一个新的数组,新数组的元素是原数组中的元素经过函数处理后的结果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CustomMap</title>
</head>
<body>
<script>
// 实现一个自定义的map函数:请编写一个函数,模仿Array对象的map()方法,接受一个数组和一个函数作为参数,返回一个新的数组,新数组的元素是原数组中的元素经过函数处理后的结果。
/**
* const numbers = [1, 2, 3, 4, 5];
* const squaredNumbers = customMap(numbers, num => num * num);
* 期望 squaredNumbers 为 [1, 4, 9, 16, 25]
*/
function customMap (array,func) {
return array.reduce((pre,item)=>{
pre.push(func(item));
return pre;
},[])
}
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = customMap(numbers, num => num * num);
console.log(squaredNumbers); //[1, 4, 9, 16, 25]
</script>
</body>
</html>