簡體   English   中英

我正在嘗試解決的初學者 Javascript 函數問題

[英]Beginner Javascript function problem I'm trying to solve

我試圖解決的問題如下:

我經常不知道在某一天我應該穿短褲還是褲子。 請幫我寫一個叫做isShortsWeather的函數來決定

它應該接受一個數字參數,我們將其稱為temperature (但您可以隨意命名)。

  • 如果temperature大於或等於 75,則返回true
  • 否則返回false
  • 此練習假設temperature為華氏度

預期結果:

isShortsWeather(80) //true
isShortsWeather(48) //false
isShortsWeather(75) //true

我寫的代碼是:

function isShortsWeather(temperature) {
    if (temperature < 75); {
        return false;
    } 
    if (temperature >= 75) {
        return true;
    }
}

作為片段:

 function isShortsWeather(temperature) { if (temperature < 75); { return false; } if (temperature >= 75) { return true; } } console.log(isShortsWeather(80)) //true console.log(isShortsWeather(48)) //false console.log(isShortsWeather(75)) //true

請通過告訴我我的代碼有什么問題以及我應該如何解決這個問題來幫助我。 我覺得我比較接近解決它。 謝謝!

只需返回布爾值:

return temperature >= 75;

它不起作用的主要原因是因為你有一個額外的; 在第一個條件之后。 您可以將函數體縮短為一行

function isShortsWeather(temperature) {
    return temperature >= 75;
}

你忘記了; 在第 2 行,如果您將其刪除,它將起作用。 此外,如果您在else if進行第二個 if 語句會更好

    function isShortsWeather(temperature) {
        if (temperature < 75) {
            return false;
        } else if (temperature >= 75) {
            return true;
    }

我建議同時返回 if 語句,而不是控制台登錄 false。 您將使用 console.log 來調用該函數。 由於不需要第 2 行的分號,我對代碼進行了一些編輯。

 function isShortsWeather(temperature) { if (temperature < 75) { return false; } else { return true; } } temperature = 74; console.log(isShortsWeather(temperature));

您將在下面找到正在運行的正確代碼。 希望回答你的問題。

 function isShortsWeather(temperature) { if (temperature >= 75) { return true; } else { return false; } } console.log(isShortsWeather(76)); console.log(isShortsWeather(74));

您可以返回值而不是控制台記錄它。

將“幻數” 75重構為具有默認值的變量也是一個好主意,以便您以后輕松更改或覆蓋它。

function isShortsWeather(temperature, cutoffTemp = 75) {
  if (temperature < cutoffTemp) {
    return false;
  } 
  if (temperature >= cutoffTemp) {
    return true;
  }
}

console.log(isShortsWeather(81));
function isShortsWeather(temperature) {

if (temperature < 75); {return 0;}

if (temperature >= 75) {return 1;}
}

我認為這會解決你的問題

暫無
暫無

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

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