累加器在Javascript中的reduce fcuntion中返回NaN

时间:2018-06-12 00:30:21

标签: javascript higher-order-functions

我正在学习使用扩展运算符 class ImportCsvController < ApplicationController before_action :require_user before_action :require_admin def index # get the last 5 import history for dashboard @Fileimport = FileUploadInfo.order('updated_at DESC').limit(5) end # Import CSV file def import_csv_datei begin user=current_user.user_name time = Time.now status= "OK" filepath = params[:file] @file = FileUploadInfo.new @file.filename = filepath.original_filename @file.importdate = time.to_formatted_s(time) @file.status = status @file.username = user if @file.save #Import Successful #FileUploadInfo.import_file(params[:file],time.to_formatted_s(time),"erfolgreich",user) redirect_to :back, notice: "Import Erfolgreich!" else #return errors #format.html {render :index} #format.json {render json: {status:"Fehler: ",message: "Dateiformat ist nicht erlaubt!"}} redirect_to :back, notice: "Fehler" end rescue redirect_to root_path, notice: "Invalid CSV file format." end end end 来编写一个函数,该函数接受传递给函数的所有参数并返回偶数参数的总和。我的问题是为什么我的acc等于NaN,除了reduce()的第一个回调?

代码和执行的打印输出如下,...是我插入的调试代码。谢谢你的帮助。

console.log(...)

输出:

 function sumEvenArgs(...args){
  var sum = args.reduce( (acc, next) => {
    console.log("\nnext:", next);
    if (next % 2 === 0) {
      acc += next;
      console.log("in if - acc:", acc);
    } else {
      acc += 0;
      console.log("in else - acc:", acc);
    }
  }, 0);

  return sum;
}
var sum = sumEven(1,2,3,4) // 6
console.log("sum:", sum);

1 个答案:

答案 0 :(得分:1)

您应该在回调函数结束时返回 acc

&#13;
&#13;
function sumEvenArgs(...args){
    var sum = args.reduce( (acc, next) => {
        console.log("\nnext:", next);
        if (next % 2 === 0) {
            acc += next;
            console.log("in if - acc:", acc);
        } else {
            acc += 0;
            console.log("in else - acc:", acc);
        }
        return acc ; // you need to add this line 
    }, 0);

    return sum;
}
var sum = sumEvenArgs(1,2,3,4) // 6
console.log("sum:", sum);
&#13;
&#13;
&#13;