📅  最后修改于: 2023-12-03 15:27:40.092000             🧑  作者: Mango
本问题考察对 JavaScript 中对象和函数的理解。
假设有一个 person
对象,它有如下属性和方法:
const person = {
name: 'Jack',
age: 25,
lightSleepHours: 7,
deepSleepHours: 3,
sleep: function (hours) {
this.lightSleepHours += hours * 0.8;
this.deepSleepHours += hours * 0.2;
}
};
请编写一个函数 getSleepQuality
,它的参数是一个 person
对象,返回该人睡眠质量的评级。评级规则如下:
我们可以使用下面的代码来实现该函数:
function getSleepQuality(person) {
const totalSleepHours = person.lightSleepHours + person.deepSleepHours;
if (totalSleepHours < 7) {
return 'Poor';
} else if (totalSleepHours >= 7 && totalSleepHours <= 8) {
const deepSleepRatio = person.deepSleepHours / totalSleepHours;
if (deepSleepRatio < 0.3) {
return 'Average';
} else if (deepSleepRatio >= 0.3 && deepSleepRatio <= 0.5) {
return 'Good';
} else {
return 'Excellent';
}
} else {
return 'Good';
}
}
我们可以使用下面的代码对该函数进行测试:
const person1 = {
name: 'Tom',
age: 28,
lightSleepHours: 6,
deepSleepHours: 2
};
const person2 = {
name: 'Alice',
age: 31,
lightSleepHours: 5,
deepSleepHours: 4
};
const person3 = {
name: 'Bob',
age: 24,
lightSleepHours: 7,
deepSleepHours: 3
};
console.log(getSleepQuality(person1)); // Poor
console.log(getSleepQuality(person2)); // Average
console.log(getSleepQuality(person3)); // Excellent
本问题考察了 JavaScript 中对象和函数相关知识,同时也考察了我们的逻辑思维能力。掌握这些知识和技能,有助于我们更好地进行 JavaScript 开发。