gpt4 book ai didi

javascript - 循环对象数组以返回正确的结果

转载 作者:行者123 更新时间:2023-11-30 20:04:20 25 4
gpt4 key购买 nike

我有一个包含对象的数组:

 next: [
{
max_score: 5,
outcome: "rest_and_come_back_later"
},
{
max_score: 49,
outcome: "see_a_doctor"
},
{
outcome: "go_to_emergency_room"
}
]

还有一个包含 patientScore 的变量,假设 patientScore 是 70。如果分数小于 5,它应该返回结果 rest_and_come_back_later,如果是 max_score 49,它应该返回正确的结果。如果它高于 49,它应该返回结果:go_to_emergency_room。

在 javascript 中执行此操作的最佳方法是什么?

简单的 ifelse 能完成这项工作吗?像这样:

next.forEach((item) => {
if(patientScore < item.max_score && patientScore >= item.max_score){
return console.log("max_score: " + item.max_score)
}else if(patientScore > item.max_score){ return console.log("max_score: " + item.max_score)}})

最佳答案

  1. 您将返回一个未定义的值 return console.log(...)不仅如此,还在您用于函数 Array.prototype.forEach 的处理程序内部这是没有意义的。
  2. 另一种方法是对数组进行排序,然后生成 <=比较才能找到合适的对象max_score .

let next = [{      max_score: 5,      outcome: "rest_and_come_back_later"    },    {      max_score: 49,      outcome: "see_a_doctor"    },    {      outcome: "go_to_emergency_room"    }  ],
// Sort the array to avoid multiple OR conditions.
array = next.slice().sort((a, b) => {
if (!('max_score' in a)) return Number.MAX_SAFE_INTEGER;
if (!('max_score' in b)) return Number.MIN_SAFE_INTEGER;
return a.max_score - b.score;
}),
// This function finds the specific 'outcome' just comparing the
// current index.
findDesc = (arr, score) => {
for (let i = 0; i < arr.length; i++) {
if (score <= arr[i].max_score) return arr[i].outcome;
}
return arr.slice(-1).pop().outcome;
}

console.log(findDesc(array, 4));
console.log(findDesc(array, 5));
console.log(findDesc(array, 48));
console.log(findDesc(array, 49));
console.log(findDesc(array, 50));
console.log(findDesc(array, 70));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 循环对象数组以返回正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53074229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com