首页 > 解决方案 > 返回“未定义”的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?'
}

标签: javascriptarraysdata-structuresnested-listsundefined-function

解决方案


有没有更好的方法来写这个?

我会做:

function getLetterGrade(score) {
  return ['F', 'F', 'E', 'D', 'C', 'B', 'A'][Math.ceil(score / 5)];
}

F出现两次,因为更多的分数映射到 F 比其他等级)

它可能有点神秘,但如果可能的分数发生变化,它更容易调整。


推荐阅读