微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript-在传递函数作为参数时使用reduce,错误实现地图函数

如何解决JavaScript-在传递函数作为参数时使用reduce,错误实现地图函数

我正在尝试使用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()"

            >&times;</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>

错误输出为:“ TypeError:fn不是函数

所以我的问题是-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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。