问题描述
我正在尝试使用reduce在JavaScript中实现地图功能。
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8" />
<Meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;1,100&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<header>
<img src="logo/logo.png" alt="" />
<div class="container" onclick="openBtn()">
<div class="line-1"></div>
<div class="line-2"></div>
<div class="line-3"></div>
</div>
<nav>
<ul>
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()"
>×</a
>
<li><a href="index.html">Home</a></li>
<li><a href="pages/about.html">About us</a></li>
<li><a href="pages/contact.html">How to reach me</a></li>
<li><a href="pages/portfolio.html">Portfolio</a></li>
</ul>
</nav>
<section class="sm">
<a href="#"><i class="fab fa-facebook-f" class="facebook"></i></a>
<a href="#"><i class="fab fa-twitter" class="twitter"></i></a>
<a href="#"><i class="fab fa-google" class="google"></i></a>
</section>
<main></main>
<section></section>
<footer></footer>
</header>
</body>
<script src="js/script.js"></script>
<script
src="https://kit.fontawesome.com/dd4d991431.js"
crossorigin="anonymous"
></script>
所以我的问题是-reduce函数签名或传递的函数抛出错误,我在做什么错?
P.S。 -仍在学习javascript,如果有人可以帮助编辑标题以使其更清晰,那将不胜感激。
谢谢
解决方法
您在传递library(tidyverse)
mpg %>% ggplot(aes(x = cty,y = cyl)) + geom_point() + theme_classic() +
theme(line = element_line(size = 4,color = "black",lineend = "square"),text = element_text(color = "black",face = "bold",size = 24))
时调用它,但是您只需要在reduce回调中调用Delete-User - - <<include>> - -> Create-User
。在reduce回调内部,将plusTwo
的调用添加到累加器数组上。
plusTwo
,
您传递来减少的回调将返回一些信息。加上其他人的评论,您想传递{{1}(plusTwo
的结果)plusTwo()
,而不是NaN
:
undefined+2
,
-
mapItem
是对结果数组的引用。您需要将结果值推送到该值,而不是在每次迭代中都重新分配它,即mapItem.push(fn(elem))
- 将
plusTwo
作为函数传递而不是调用plusTwo()
,这就是为什么出现fn is not a function
错误的原因 - 打印
newMap
而不是newMap
本身的结果
function newMap(inputArr,fn) {
return inputArr.reduce((mapItem,elem) => {
mapItem.push(fn(elem))
return mapItem;
},[])
}
function plusTwo(num) {
return num + 2;
}
let result = newMap([1,2,3],plusTwo)
console.log(result)