switch语句未返回期望值

时间:2019-05-12 16:26:48

标签: javascript switch-statement

我试图根据ages数组返回'Can drink''Wait',但是我的switch语句出了点问题,我得到了'Try again'

var yearsArr = [1992, 1980, 2004, 2010];

function getAge(arr, fn) {
    var arrRes = [];
    for(var i = 0; i < arr.length; i++) {
        arrRes.push(fn(arr[i]));
    }
    return arrRes;
}

function calcAge(el) {
    return 2019 - el;
}

var ages = getAge(yearsArr, calcAge);
console.log(ages);

function canDrink(el) {
    switch(el) {
        case el >= 18:
            return 'Drink'
        break;
        case el < 18:
            return 'Wait'
        break;
        default:
            return 'Try again!'
    }
}

var drinkArr = getAge(ages, canDrink);
console.log(drinkArr);
// result = ["Try again!", "Try again!", "Try again!", "Try again!"]

3 个答案:

答案 0 :(得分:4)

您需要使用true作为值来检查case部分的结果。

switch (true) {    // <---------------------for--+
    case el >= 18: // -> returns a boolean value-+

答案 1 :(得分:3)

您没有在switch语句中比较正确的值。

让我们想象使用一些值,我们用参数canDrink调用17

function canDrink(el) { //Receives 17
    switch (el) { //Handles 17 as main value
        case el >= 18: // 17 >= 18 is false, but true===17 is false
            return 'Drink'
            break;
        case el < 18: // 17<18 is true, but false===17 is false
            return 'Wait'
            break;
        default: // So, none of the conditions matches default executes.
            return 'Try again!'
    }
}

您该如何适应?

function canDrink(el) { // el = 17
    switch (true) { // We use true as our main value
        case el >= 18: // 17>=18 is false, so our main value true === false, not executed
            return 'Drink'
            break;
        case el < 18: // 17<18 is true, so true===true, executes this.
            return 'Wait'
            break;
        default:// No need for default.
            return 'Try again!'
    }
}

您可以选中this working example

答案 2 :(得分:3)

在这种情况下,我将使用if / else语句代替switch。 :-)

// Returns the age for a birthYear
function getAge(birthYear) {
    return (new Date()).getFullYear() - birthYear;
}

// Returns the tapper's response for an age value
function getTapperResponse(age) {
    if (age >= 18) {
        return 'Drink';
    } else {
        return 'Wait';
    }
}

const birthYears = [1992, 1980, 2004, 2010];

const ages = birthYears.map(by => getAge(by));
console.log(ages);

const tapperResponses = ages.map(a => getTapperResponse(a));
console.log(tapperResponses);