我有一个对象数组:
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)}})
答案 0 :(得分:1)
return console.log(...)
,不仅如此,而且还返回了用于函数Array.prototype.forEach
的没有意义的处理程序内部。<=
比较,以找到具有正确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; }
答案 1 :(得分:0)
最简单的方法是按照正确的顺序定义得分数组,然后使用Array.prototype.find返回score <= item.max_score
const list = [
{
max_score: 5, outcome: "rest_and_come_back_later"
},
{
max_score: 49, outcome: "see_a_doctor"
},
{
max_score: Infinity, outcome: "go_to_emergency_room"
}
];
function test(score) {
// Here it is:
const item = list.find(i => score <= i.max_score);
console.log(item.outcome);
}
const testScores = [1, 5, 12, 50, 100];
testScores.forEach(test);
答案 2 :(得分:0)
如果我理解您的问题正确,那么解决此问题的一种方法可能是定义一个函数getOutcome()
,如下所示。
此方法根据传递的输入patientScore
参数返回所需结果:
var object = {
next : [
{
max_score: 5,
outcome: "rest_and_come_back_later"
},
{
max_score: 49,
outcome: "see_a_doctor"
},
{
outcome: "go_to_emergency_room"
}
]
};
function getOutcome (score) {
return object.next.filter(item => {
if(score < 5) {
return (item.max_score <= 5)
}
else if(score > 49) {
return (item.max_score >= 49)
}
else {
return (item.max_score > 5 && item.max_score < 49) || (item.max_score === undefined)
}
}).map(item => item.outcome)[0]
}
console.log('patientScore = 70', getOutcome(70) );
console.log('patientScore = 3', getOutcome(3) );
console.log('patientScore = 25', getOutcome(25) );