Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将for循环作为数组中的对象插入的语法_Javascript_Angularjs_Ionic Framework - Fatal编程技术网

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

Javascript 将for循环作为数组中的对象插入的语法,javascript,angularjs,ionic-framework,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], $sco

这是我拥有的数据的一个示例:

$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
}

};

所以我只需要循环上面的数组,把所有的时间加起来就可以得到每个播放列表的总时间(mostpopular[0]。time+=totalTime然后mostpopular[1]。time+=totalTime等等……或者类似的东西)。这可能吗?如果可能,语法是什么?提前感谢

您可以使用reduce函数来实现这一点

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

reduce函数使用累加器(totalTime),然后使用数组中当前值的第二个参数。底部的0表示我们应该使用什么作为初始totalTime参数。然后在reduce中更改totalTime后,返回值将成为数组中下一项的totalTime参数。

对此表示抱歉:)