初学者:检查参数和整数

时间:2016-03-23 12:50:17

标签: javascript parameters integer

所以这是个问题: 编写一个名为daySuffix的函数,它接受一个参数。检查该参数以确保它是一个数字(请参阅Number.isNaN(),然后转换为最接近的整数。检查整数是否在1到31的范围内。如果其中一个检查失败,则返回值null最后应该在月份后缀的适当日期返回整数(例如,“1st”,“2nd”,“3rd”,“27th”等)。仅使用一个返回语句(总共三个) )

var daySuffix = function() {
    var num1 = 100;

    if (typeof num1 == 'number') {
        document.write(num1 + " is a number <br/>");
    } else {
        document.write(num1 + " is not a number <br/>");
    }

    function between(daySuffix, min, max) {
        return daySuffix >= min && daySuffix <= max;
    }
    if (between(daySuffix, 1, 31)) {

    };

    console.log()
};

daySuffix()

显然我有点失落。谁能给我一个关于从哪里去的提示?

3 个答案:

答案 0 :(得分:0)

//function with a parameter
var daySuffix = function (num1) {
    if (isNaN(num1)) {
       //not a number, return null
       return null;
    }

    if (num1 < 1 || num1 > 31) {
        //outside range
        return null;
    }

    //logic for finding suffix
}

console.log(daySuffix(0));     //null
console.log(daySuffix(1));     //"1st"
console.log(daySuffix("hi"));  //null

答案 1 :(得分:0)

以下是一份工作样本:

var daySuffix = function (num) {
    var result = null,
        days = ["st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"];

    if (!isNaN(num)) {
        num = Math.round(num);
        if (num >= 1 && num <= 31) {
            result = num + days[num - 1];
        }
    }
    return result;
}

答案 2 :(得分:0)

这是另一个可能适合您的解决方案:

var daySuffix = function(num) {
    var stringEquivalent, last2Digits, lastDigit;
    var suffixes = ['th', 'st', 'nd', 'rd', 'th'];
    var roundedNum = Math.round(num);

    // Check to see if `num` is a number and between the values of 1 and 31
    if (typeof num === 'number' && roundedNum >= 1 && roundedNum <= 31) {

        // Convert to string equivalent
        stringEquivalent = String(roundedNum);

        // Get the last 2 characters of string and convert them to number
        last2Digits = Number(stringEquivalent.slice(-2));

        lastDigit = Number(stringEquivalent.slice(-1));

        switch (last2Digits) {

            // 11, 12, and 13 have unique 'th' suffixes
            case 11:
            case 12:
            case 13:
                return roundedNum + 'th';
            default:
                return roundedNum + suffixes[Math.min(lastDigit, 4)];
        }
    }

    // Null is returned if the 'if' statement fails
    return null;
};
// Test results
for (var i = 1; i <= 31; i++) { console.log(daySuffix(i)); }