簡體   English   中英

freeCodeCamp 挑戰指南:使用 reduce 方法分析數據

[英]freeCodeCamp Challenge Guide: Use the reduce Method to Analyze Data

我在 freeCodeCamp 使用 reduce 方法分析數據挑戰

我試過了:

function getRating(watchList){
  // Add your code below this line
  var count = 0;
  var sum = 0;
  var averageRating = watchList.reduce(function (obj)  {
    if (obj.Director === "Christopher Nolan") {
      count++;
      
      sum =  sum + parseFloat(obj.imdbRating);
      
    }
    
    return sum;
  }, 0) / count;
  // Add your code above this line
  return averageRating;
}

結果是NaN,我做錯了什么? 我必須使用箭頭 function,因為標准的 function 聲明產生了意想不到的結果?

感謝幫助

我會給你提示。

const res = watchList.filter((d) => d.Director === 'James Cameron').map(x => x.averageRating));

然后另一個 map 轉數字

 res.map(Number)

現在使用 reduce 來計算數字的平均值。 一切都在這里解釋。

你可以試試:

const relevant = watchList.filter(movie => movie.Director === "Christopher Nolan");
const total = relevant.reduce((sum, movie) => sum + Number(movie.imdbRating), 0);
const average = total / relevant.length;

或結合最后兩行:

const relevant = watchList.filter(movie => movie.Director === "Christopher Nolan");
const average = relevant.reduce((sum, movie) => sum + Number(movie.imdbRating), 0) / relevant.length;
function getRating(watchList){
  // Add your code below this line
  var titles = watchList.filter(function(obj){
return obj.Director === "Christopher Nolan";
});
//message(titles);
var averageRating = titles


.reduce( function(sum,obj){
  return sum = sum + parseFloat(obj.imdbRating);
}, 0)/titles.length;
  //message(watchList.Director);
   
  // Add your code above this line
  return averageRating;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM