有没有办法可以更有效地实现此代码?因为循环一个很大的分数数组只是为了找到一个分数属性是非常昂贵的

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

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

最佳答案

最有效的方法是使用对象而不是键为scoredBy值的数组。没有循环,只是一个查找。



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





其他方法


for of loop with break
array find()




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);

关于javascript - 在对象数组中循环播放属性的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44520967/

10-11 19:34
查看更多