2016-11-26 81 views
-3

插入一个for循环作为对象这是数据的一个例子,我有:语法在阵列

$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 then mostpopular [1] .time + = totalTime等....或类似的东西)。这是可能的,如果是这样,语法是什么?由于事先

+0

对不起,:) – MehdiN

回答

0

可以使用减少函数,该函数

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

减少函数使用的储液器(TOTALTIME),然后将第二个参数在所述阵列中的当前值。底部的0表示我们应该使用什么作为初始totalTime参数,然后在reduce return中改变totalTime,这将成为数组中下一项的totalTime参数。