2017-05-02 46 views
0

我有這個蒙戈集合opponents存儲每個玩家的對手更新收集的詳細

{username:foo, foo:{foo1:0,foo2:0,foo3:0}} 
{username:foo1,foo1:{foo:0,foo2:0,foo3:0}} 
{username:foo2,foo2:{foo:0,foo1:0,foo3:0}}//i.e player foo2 play 0 games with foo,foo1 and foo3 

而且在Node.js的服務器端解決此table對象:

var table =[{name:"foo",rounds:3},{name:"foo1",rounds:3},{name:"foo2",rounds:3},{name:"foo3",rounds:3}] //all players' name in a table with their rounds number 

對於表格中的每位玩家,我希望將其對手的名字和回合追加到opponent集合(當然不需要追加他們自己)。期望的結果是:

{username:foo, foo:{foo1:3,foo2:3,foo3:3}} 
{username:foo1,foo1:{foo:3,foo2:3,foo3:3}} 
{username:foo2,foo2:{foo:3,foo1:3:foo3:3}} 
{username:foo3,foo3:{foo:3,foo1:3,foo2:3}} 

我有一個自定義函數fun(name)來爲每個玩家返回一個他們對手名字的數組。所以fun(table[0].name)將返回[foo1,foo2,foo3]

function fun(name){ 
    var result = []; 
    for (var i = 0; i <players.length; i++){ 
     if(players[i].name!=name){ 
     result.push(players[i].name) 
     } 
     } 
     return result; 
} 

這是我當前的代碼:

 for (var i =0;i<table.length;i++){ 
     db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[0] ] :table[i].rounds}}) 
     if (table.length>2){ 
     db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[1] ] :table[i].rounds}}) 
    } 
    if (table.length>3){ 
     db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[2] ] :table[i].rounds}}) 
    } 

但它是剛性的硬編碼,如果table.length增加我需要更多的代碼行。我如何使用變量來使它更緊湊?我試圖使用嵌套循環,但這使得它變得更糟。

回答

0

問題解決了:

for (var i = 0; i < table.length; i++) { 
    db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[0] ] :table[i].rounds}}) 
    for (var j = 1;j<fun(table[i].name).length;j++){ 
     db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[j] ] :table[i].rounds}}) 
    } 
    }