将for循环插入数组中的对象的语法

时间:2016-11-26 20:16:51

标签: javascript angularjs ionic-framework

这是我的数据示例:

$scope.allmovies[
{title:"Harry Potter", time:130},
{title:"Star Wars", time:155},
{title:"Lord of the Rings", time:250},
{title:"Goonies", time:125},
{title:"Fast and Furious", time:140}
];

var mostpopular=[
$scope.allmovies[0],
$scope.allmovies[2]
];

var recentlyadded=[
$scope.allmovies[1],
$scope.allmovies[3],
$scope.allmovies[4]
];

$scope.playlists={

mostpoplularmoves:{
title:"Most Popular Movies",
price:"$5.99",
Number:mostpopular.length,
TotalTime: LOOP THROUGH VAR MOSTPOPULAR AND ADD TIME TO GET A TOTAL TIME OF ALL MOVIES
},

recentlyaddedmovies:{
title:"Recently Added Movies",
price:"$2.99",
Number:recentlyadded.length,
TotalTime:LOOP THROUGH VAR RECENTLYADDED AND ADD TIME TO GET A TOTAL TIME OF ALL MOVIES
}

};

所以我只需要遍历上面的数组,并将所有时间相加以获得每个播放列表的总时间(最流行[0] .time + = totalTime然后最流行[1] .time + = totalTime等... 。 或类似的东西)。这是可能的,如果是这样,那么语法是什么?提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用reduce函数

mostpopular.reduce(function(totalTime, movie) {
  return totalTime + movie.time;
}, 0);

reduce函数使用累加器(totalTime),然后使用数组中当前值的第二个参数。底部的0表示我们应该使用的初始totalTime参数。然后在reduce return中改变totalTime,这将是数组中下一个项目的totalTime参数。