简体   繁体   English

Switch语句不返回所需的值

[英]Switch statement doesn't return the desired value

I am trying to return 'Can drink' or 'Wait' based on the ages array but something is wrong with my switch statement, I am getting 'Try again' . 我试图根据年龄数组返回'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!"] 

You need to use true as value to check with the results of the case parts. 您需要使用true作为值来检查case部分的结果。

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

You are not comparing correct values in your switch statement. 您没有在switch语句中比较正确的值。

Lets imagine using some values, we call canDrink with parameter 17 . 让我们假设使用一些值,我们用参数17调用canDrink

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!'
    }
}

How should you adapt this? 你应该如何适应这个?

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!'
    }
}

You can check this working example . 您可以查看此工作示例

I would use an if / else statement instead of a switch in this case. 在这种情况下,我会使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM