我面临着一个我从未见过的问题。我不需要最低值,但我需要有最低值的变量。
我有5个变量,假设它们是这样设置的(显然不是这样):
rat_professionalism_pct = 57.1
rat_responsiveness_pct = 58.6
rat_expertise_pct = 61.0
rat_courtesy_pct = 44.4
rat_teamplayer_pct = 50.9我的目标是有这样一个句子:
你的最高评价属性是“专业知识”。
我的标准做法是:
let rat_attribute;
let rat_pct;
let rat_attribute_highest = 'professionalism';
let rat_pct_highest = per_rat_professionalism_pct;
for (let b = 1; b <= 5; b++) {
switch (b) {
case 1: rat_attribute = 'professionalism'; rat_pct = per_rat_professionalism_pct; break;
case 2: rat_attribute = 'responsiveness'; rat_pct = per_rat_responsiveness_pct; break;
case 3: rat_attribute = 'expertise'; rat_pct = per_rat_expertise_pct; break;
case 4: rat_attribute = 'courtesy'; rat_pct = per_rat_courtesy_pct; break;
case 5: rat_attribute = 'professionalism'; rat_pct = per_rat_professionalism_pct; break;
}
if (rat_pct > rat_pct_highest) {
rat_attribute_highest = rat_attribute; rat_pct_highest = rat_pct;
}
}这是一种独立于语言的方法,可以在任何编程语言中工作,因为它只使用条件和循环的基本模式。
但是,我认识到我是Javascript的新手,不会(默认情况下)跳到JS的一些最酷的函数,比如数组函数。
是否有更好的方法来做到这一点,例如,使用.reduce()?
发布于 2020-07-15 15:03:55
为什么不把所有的变量作为键放在一个对象中,然后找到最大值和与该最大值相关联的键?
const obj = {
professionalism: 57.1,
responsiveness: 58.6,
expertise: 61.0,
courtesy: 44.4,
teamplayer: 50.9
}
const maxValue = Math.max(...Object.values(obj));
for (const k of Object.keys(obj)) {
if (obj[k] == maxValue) {
console.log(`Your highest rated attribute is '${k}'`);
break;
}
}
以下是另一种可以达到预期结果的方法
const obj = {
professionalism: 57.1,
responsiveness: 58.6,
expertise: 61.0,
courtesy: 44.4,
teamplayer: 50.9
}
let key = '', value = -1;
for (const [k, v] of Object.entries(obj)) {
if (v > value) {
key = k;
value = v;
}
}
console.log(`Your highest rated attribute is '${key}'`);
发布于 2020-07-15 15:12:32
一条邮轮,取自:Getting key with the highest value from object
const obj = {
professionalism: 57.1,
responsiveness: 58.6,
expertise: 61.0,
courtesy: 44.4,
teamplayer: 50.9
};
const maxKey = Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
console.log(`Your highest rated attribute is '${maxKey}'`);如果某些变量相等,它将保留第一个遇到的变量。
https://stackoverflow.com/questions/62917789
复制相似问题