【问题标题】:Javascript Using callback in Array Method with .mapJavascript 在 .map 的数组方法中使用回调
【发布时间】:2019-03-21 18:04:58
【问题描述】:

我有这个练习,我需要帮助来了解我哪里出错了。到目前为止,这是我的代码。

// Exercise Two: In this exercise you will be given an array called 'cents'
// This array is a list of prices, but everything is in cents instead of dollars.
// Using the map method, divide every value by 100 and save it as a new array 'dollars'

function exerciseTwo(cents){ 

    function mapMethod(array, cb) { // created the map method
      let dollars = [];   // declaring the new array 'dollars'
        for (i=0; i < array.length; i++) { //iterating through the loop
          let updatedValue = cb(array[i] / 100); // dividing the iteration by 100
          dollars.push(updatedValue); //pushing the updated value to the new array 'dollars'
         }
          return dollars; 
    }
        // Please write your answer in the lines above.
          return dollars; // getting error that 'dollars' is not defined :(
}

【问题讨论】:

  • 你应该使用原生js map() method.
  • 欢迎来到 Stack Overflow!请拿起tour,环顾四周,通读help center,尤其是How do I ask a good question? 分配通常不是任意的;您的讲师、教程或课程将涵盖使您能够做到这一点的必要主题。 查看您的课程资料、课堂笔记等,并尝试一下。 如果您遇到特定问题,请彻底研究, search thoroughly,如果您仍然遇到问题,请发布您的代码和具体问题的描述。人们会很乐意提供帮助。
  • 你没有在代码中的任何地方调用你的函数mapMethod,而且美元是在mapMethod范围而不是exerciseTwo范围中定义的

标签: javascript arrays methods callback


【解决方案1】:

我认为你应该区分声明和调用函数。

function square(x) {
  return x*x;
} // <-- This is declare  

square(3) // <-- This is call

您在上面的代码中所做的只是在exerciseTwo 函数中声明一个mapMethod 函数,该函数将在系统运行测试时被调用。但是你的mapMethod 函数不会被调用,只是定义而已。

内部函数可以使用外部函数的变量,反之则不行。那么你不能从外部函数exerciseTwo()返回在内部函数mapMethod()中声明的dollars

遵循要求。您应该使用map 方法简化您的代码。

function exerciseTwo(cents){
  const dollars = cents.map(cent => cent/100)
  return dollars
}

【讨论】:

  • 谢谢,我想得太多了。我确实想知道您为什么使用“const”变量而不是“var”或“let”。我通过各种来源进行的其他解释似乎都倾向于“让”。
  • 第一个var 是函数作用域,letconst 是块作用域。它建议使用letconst 而不是var。你可以在网上搜索一下为什么。其次,我将const 用于不可变数据,它会阻止您重新分配dollars 变量。 const a=[1,2,3]; a =[4,5] ~&gt; cause errorlet 不会。这就是为什么我使用const
【解决方案2】:

-您遇到此错误是因为您试图返回美元,而美元在您的主函数中不存在,这是无效的:

let updatedValue = cb(array[i] / 100);

这样做:

let updatedValue = cb(cents[i] / 100);

但你看不到美分,因为你没有在函数内声明它

【讨论】:

  • 对不起,我是这个平台的新手
  • 没什么大不了的。我添加了空格来格式化代码块。
【解决方案3】:

这是作者编写的首选代码。显然还有更多“剥猫皮的方法”。

  const dollars = cents.map(function(price){
return price/100;

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 2017-08-14
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2019-12-19
    相关资源
    最近更新 更多