簡體   English   中英

開關返回值未定義

[英]Switch return value is undefined

當我通過 .html 文件從 Notepad++ 運行此代碼時,輸​​出無法識別我的返回值。 它總是輸出“未定義”

我試過將 return 語句放在 switch 語句之外,但它沒有解決任何問題。

編輯:我包含了調用該函數的代碼,並根據 iCode 的提示修復了我的 if 語句。

// this came with the execrise
var sentinel = true

while (sentinel) {

    var month = prompt("Enter an integer from 1 to 12 inclusive, representing a month of the year");
    var request = prompt("Enter 1 if you want the name of the month, or enter 2 if you want the number of days in the month");

    if (months(month,request) == false) {
        // reset
        alert("Try again but enter the right stuff this time");

    } else {
        // output
        sentinel = false;

        if (request == 1) {

            console.log("Month number " + month + " is " + months(month,request));

        } else if (request == 2) {

            console.log("There are " + months(month,request) + " days in month number " + month);
        }
    }
}

// this is my edited code
function months(month,request) {
    if (!request || request < 1 || request > 2 || isNaN(request)) {
        return false;
    }
    if (!month || month < 1 || month > 12 || isNaN(month)) {
        return false;
    }

    var name;
    var numberDays;
    switch(month){
        case 1:
            if(request == 1){
                name = "January";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 2:
            if(request == 1){
                name = "February";
                return name;
            }else{
                numberDays = "28";
                return numberDays;
            }
            break;

        case 3:
            if(request == 1){
                name = "March";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 4:
            if(request == 1){
                name = "April";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 5:
            if(request == 1){
                name = "May";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 6:
            if(request == 1){
                name = "June";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 7:
            if(request == 1){
                name = "July";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 8:
            if(request == 1){
                name = "August";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 9:
            if(request == 1){
                name = "September";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 10:
            if(request == 1){
                name = "October";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 11:
            if(request == 1){
                name = "November";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 12:
            if(request == 1){
                name = "December";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
    }
}

                return false;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

我希望輸出是“第 1 個月是 1 月”或“第 1 個月有 31 天”

簡化您的代碼。 需要年份才能准確地獲得二月的天數。

創建一個新日期 ( new Date(2019, 1, 0) ) 並將 day 參數設置為 0 會將其設置為該月的最后一天。

 function months(month, request = 1, year){ if(year === undefined) year = (new Date()).getYear(); const d = new Date(year, month, 0); return request === 1 ? d.toLocaleString('en-us', { month: 'long' }) : d.getDate(); } const res0 = months(5); const res1 = months(1,0); const res2 = months(2,0); const res3 = months(3,0); console.log(res0, res1, res2, res3);

意外結果的解釋

此代碼返回undefined的原因是因為您有一個沒有任何返回值的未處理案例。 每個if語句都帶有自己的else語句return false 所以那里沒有問題。 但是switch語句不處理default情況。 這是唯一沒有返回值的地方,所以這一定是問題所在。

第一個數字的字符串輸入會出現問題,因為它傳遞了if語句,但不匹配任何switch case。

 console.log("'3' <= 12 //=>", '3' <= 12); console.log("'3' >= 1 //=>", '3' >= 1); console.log("'3' == 3 //=>", '3' == 3); console.log("'3' === 3 //=>", '3' === 3); // ^ used for switch comparison

這意味着,如果您使用諸如months(3, 1) //=> "March"類的輸入運行函數,而months('3', 1) //=> undefined 首先將字符串轉換為整數以正確匹配其中一種情況。 這是因為switch case 使用了嚴格的比較

編輯后,這變得更加清晰,因為我們可以看到數據的來源。

 var month = prompt("Enter an integer from 1 to 12 inclusive, representing a month of the year"); console.log(month, typeof(month));

替代方案

隨着對意外結果的解釋。 讓我們看看一些產生類似結果的代碼。

 var monthsByNumber = { 1: { 1: "January", 2: "31" }, 2: { 1: "February", 2: "28" }, 3: { 1: "March", 2: "31" }, 4: { 1: "April", 2: "30" }, 5: { 1: "May", 2: "31" }, 6: { 1: "June", 2: "30" }, 7: { 1: "July", 2: "31" }, 8: { 1: "August", 2: "31" }, 9: { 1: "September", 2: "30" }, 10: { 1: "October", 2: "31" }, 11: { 1: "November", 2: "30" }, 12: { 1: "December", 2: "31" } }; // This allows you to access the object attributes with either // a string or a number. console.log("monthsByNumber[1] //=>", monthsByNumber[1]); console.log("monthsByNumber['1'] //=>", monthsByNumber['1']); // Introducing this into the function would look something // like this. function months(month, request) { // Normally you would define monthsByNumber here, but // in this case I needed it in my demonstration // above. // Use an empty object if it can't find the month. month = monthsByNumber[month] || {}; return month[request]; } // As you can see below this works with both numbers as well // as strings. console.log("months(1, 1) //=>", months(1, 1)); console.log("months('1', '2') //=>", months('1', '2')); console.log("months(32, 1) //=>", months(32, 1));

上面的代碼與您在當前月份函數中所期望的相同。 唯一的變化是在無效輸入的情況下返回undefined 對我來說,這比返回false更有意義。 如果我要你告訴我第 14 個月的名字,回答“我不知道”“我不能”更合適。 這就是它大致翻譯的地方。

然而,我建議更改命名,因為月份名稱和日期的鍵12分別不是很明顯。 我會選擇類似{ name: 'January', days: '31' } ,但是這需要改變兩件事之一。 request輸入也應該是"name""days" ,另一個選項是將request輸入轉換為正確的格式。 request = request == 1 ? "name" : "days" request = request == 1 ? "name" : "days" 此外,您可能還想考慮返回一個正常的天數而不是一個字符串。

JavaScript 還有一個內置的Date對象,你可能想用它來解釋閏年和其他事情,但我不會在這里詳細介紹。

@Prospective,我看到您可能在 JavaScript 中手忙腳亂。 您的樣本似乎是一個學習練習。 對你有益。 JS 是一種有趣的語言。 我將您的代碼粘貼到JS 小提琴中,但沒有出現任何錯誤(盡管我確實看到了警告)。 當然,您沒有提供用於調用月份函數的代碼。 因此,由於您調用或調用month()函數的方式,您可能會變得未定義。

正如其他人所建議的那樣,嘗試通過將一些 if 語句與 AND (&&) 或 OR (||) 條件運算符合並來降低代碼復雜性。

 var sentinel = true while (sentinel) { var month = parseInt(prompt("Enter an integer from 1 to 12 inclusive, representing a month of the year")); var request = parseInt(prompt("Enter 1 if you want the name of the month, or enter 2 if you want the number of days in the month")); var result = months(month, request); if (result == false) { // reset alert("Try again but enter the right stuff this time"); } else { // output sentinel = false; if (request === 1) { console.log("Month number " + month + " is " + result); } else if (request === 2) { console.log("There are " + result + " days in month number " + month); } } } function months(month, request) { if (!request || request < 1 || request > 2) { return false; } if (!month || month < 1 || month > 12) { return false; } var name = ""; var numberDays = 0; switch (month) { case 1: if (request === 1) { name = "January"; } else { numberDays = 31; } break; // Repeat for case 2 - 12 // ... // Include a default case though this should no longer get hit default: return -1; break; } if (request === 1) { return name; } else { return numberDays; } }

另一種建議是將變量namenumberDays的聲明移動到 switch 語句之上。 JavaScript 編譯器無論如何都會使用var關鍵字將變量聲明提升到函數的頂部。 如果您想使用更現代的 JavaScript ( ES6 ),您可以使用 let 關鍵字在塊范圍內聲明變量,就像您所做的那樣。 請注意,舊版本的 Internet Explorer 根本不支持 let 查看 caniuse.com 站點以確定瀏覽器兼容性。

另一個好的做法(雖然不是必需的)是為您返回的變量提供默認值。 然后,您可以在檢查函數的返回值時檢查默認值。

我還會使用三重等號 === 而不是 == 來檢查相等性。 例如,如果您為月份傳入“1”而不是 1,則三重等號 (===) 將不會進行類型轉換。因此,“1” == 1 為真; 而 "1" === 1 是假的。

另一個可能對您有幫助的提示。 測試 HTML/JavaScript/CSS 時,您可以使用在線站點,例如jsfiddle.netjsbin.comPlunker

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM