javascript - 返回“未定义”的Javascript函数
问题描述
我写了一个函数,它以分数为参数,应该返回字母等级。编写代码时需要遵循一些条件。即:return 'A' if 25 < score <= 30
return 'B' if 20 < score <= 25
等等。所以我想通过省略很多if-else's
. 由于我是 javascript 新手,这就是我能想到的:
// This function takes Nested arrays and a single number,
// which checks its availability in
// the inside array and then return the index of the array
function my_index(arr, score) {
for (const [index, elem] of arr.entries()) {
if (elem.includes(score)) {
return index;
}
}
}
// function to get letter grade
function getGrade(score) {
let grade;
var gradeDict = {
'A': [26, 27, 28, 29, 30],
'B': [21, 22, 23, 24, 25],
'C': [16, 17, 18, 19, 20],
'D': [11, 12, 13, 14, 15],
'E': [6, 7, 8, 9, 10],
'F': [0, 1, 2, 3, 4, 5]
}
var keys = Object.keys(gradeDict);
var values = [Object.values(gradeDict)]
grade = keys[my_index(values, score)]
return grade;
}
第一个功能工作正常。它返回嵌套数组的索引。但是 main 函数getGrade
恰好返回'Undefined'
。想不出比这更好的解决方案来减少一堆丑陋的 if-else。
var question = {
'1st': 'Can anybody help me get this done?',
'2nd': 'Is there any better way to do this?'
}
解决方案
有没有更好的方法来写这个?
我会做:
function getLetterGrade(score) {
return ['F', 'F', 'E', 'D', 'C', 'B', 'A'][Math.ceil(score / 5)];
}
(F
出现两次,因为更多的分数映射到 F 比其他等级)
它可能有点神秘,但如果可能的分数发生变化,它更容易调整。
推荐阅读
- python - 如何在 Python 中比较 2 个列表?
- java - Spring Data JPA - 创建动态查询注释
- php - morphToMany 实多对多关系
- postgresql - 当PostgreSQL中的where子句为空时,如何不依赖于where子句中的条件进行查询?
- algorithm - 如何推导出 Heapify 算法的最坏情况时间复杂度?
- bootstrap-4 - Bootstap d-md-block 在导航选项卡中导致带有图标和文本的新行
- javascript - 如何组合对象的两个键
- java - 如何转换 JEXL 表达式的类型?
- mysql - 无法登录到 Wamp 服务器中的 phpMyadmin
- serverless-framework - 从无服务器函数中获取 SQS URL 名称?