有没有办法以更有效的方式实现此代码?因为在一个非常大的分数数组上循环只是为了找到一个得分属性是非常昂贵的
var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];
scores.forEach(score=>{
if(score.scoredBy == "youssef"){
console.log(score);
}
})
答案 0 :(得分: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);