簡體   English   中英

Switch語句不返回所需的值

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

我試圖根據年齡數組返回'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!"] 

您需要使用true作為值來檢查case部分的結果。

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

您沒有在switch語句中比較正確的值。

讓我們假設使用一些值,我們用參數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!'
    }
}

你應該如何適應這個?

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

您可以查看此工作示例

在這種情況下,我會使用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