有没有一种方法可以更有效地实现此代码?因为在一个非常大的分数数组上循环只是为了找到一个分数属性是非常昂贵的
var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];
scores.forEach(score=>{
if(score.scoredBy == "youssef"){
console.log(score);
}
})
最佳答案
最有效的方法是使用对象而不是数组,其中键是 ScoreBy 值。没有循环,只是查找。
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);
关于javascript - 循环对象数组中的属性的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44520967/