2017-06-13 83 views
0

有沒有辦法以更高效的方式實現這些代碼?因爲循環在一個非常大比分陣只是爲了找到一個得分屬性是非常昂貴的在對象數組中循環屬性的最有效方法是什麼?

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}]; 

scores.forEach(score=>{ 
    if(score.scoredBy == "youssef"){ 
     console.log(score); 
    } 
}) 
+2

也許使用一個循環結構,你可以在比賽中斷。 – Teemu

+0

@Teemu在條件中添加return語句應該足夠了 – Sebastianb

+1

@Sebastianb不能forEach .... – epascarello

回答

2

最有效的方法將是其中關鍵是scoredBy值使用的對象,而不是一個數組。沒有循環,只是查找。

var scores = { "youssef" : 5, "omar":3 }; 
 
console.log(scores["youssef"])

其他方式

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}]; 
 

 
for (const value of scores) { 
 
    if (value.scoredBy==="youssef") { 
 
    console.log(value.score); 
 
    break; 
 
    } 
 
}

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}]; 
 

 
var result = scores.find(value => value.scoredBy==="youssef") 
 
console.log(result.score);

相關問題