簡體   English   中英

JavaScript-Console.log返回一些內容,但返回時顯示未定義

[英]JavaScript - Console.log return something but with return it shows undefined

標題中提到的問題:console.log顯示正確的值,但是當我返回該值並通過在段落中添加一個段落(使用jQuery)將其與DOM一起顯示時,它顯示未定義...

console.log(dateTimeUTC(timeZoneStr)); 
// Shows the correct value I wanted

return  dateTimeUTC(timeZoneStr); 
// Shows undefined

因此,我想做的是:使用帶有簡單輸入文本和提交按鈕的html表單,單擊提交按鈕時,它將使用jQuery將輸入的文本保存在變量中: let variable = $('#cityName').val(); (該值應為城市名稱),因為當我獲得城市名稱值時,我要求openweathermap API向我發送json並以ms為單位提供時區的值,那么我需要將ms值轉換為小時,因此例如紐約,:時區:-14400( json.timezone / 60 / 60)因此紐約的結果是UTC-4,那么我有一個腳本可以將我的UTC事物轉換為實際日期時間,但是該腳本可以正常工作我不需要向您解釋...當該函數完成時,它會給我這樣的結果:

Tue Aug 13 2019 05:53:39 GMT + 0200對於演示來說不是很好,所以我做了一個函數,可以更好地轉換它:

year  =  timeNow.getFullYear();
month  = ('0'+(timeNow.getMonth()+1)).slice(-2);
day  = ('0'+timeNow.getDate()).slice(-2);
hour  = ('0'+timeNow.getHours()).slice(-2);
minute  = ('0'+timeNow.getMinutes()).slice(-2);
second  = ('0'+timeNow.getSeconds()).slice(-2);
showDateTimeValue  =  day  +  "/"  +  month  +  "/"  +  year  +  " - "  +  hour  +  ":"  +  minute  +  ":"  +  second;
return  showDateTimeValue;

然后,此返回值到達我執行該函數的位置,因此在名為timeZone的函數中,在那里我已經使console.log工作,但返回時它顯示未定義。

希望我能解釋得很好,如果有人可以給我一些幫助,您會明白我正在嘗試做的事情^ _ ^

編輯-完整代碼:

Index.html代碼:

<div  class="form-group">
    <label  for="cityName">Displays the local date and time according to the name of the city</label>
    <input  name="cityName"  type="text"  id="cityName"  placeholder="Enter a name of a city..."  class="form-control">
</div>
<br>
<button  type="submit"  id="submit">Submit</button>
<p  class="results"></p>

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script  src="./scripts/main.js"></script>

main.js代碼:

$(function () {
    $( "#submit" ).click(function() {

    let  city  =  $('#cityName').val();
    cityName  =  city.split(' ').join('+');
    if(cityName  ===  "") {
        $('.results').append("<p>Wrong location.</p>");
    }
    else {
       $('.results').append("<p>The date and time of "  +  city  +  " : "  +  weatherRequest("http://api.openweathermap.org/data/2.5/weather?q="  +  cityName  +  "&units=metric&appid=MyAPIkey") +'</p>'); 
    }
    });
})

功能碼:

/* Function variable */
const messageError = "You didn't enter a valid thing.";
let timeNow = new Date();
let utcOffset = timeNow.getTimezoneOffset();
timeNow.setMinutes(timeNow.getMinutes() + utcOffset);

// Function that gives the date and hour utc time 
function dateTimeUTC(utc) {
    if(typeof utc === 'string' && utc.length >= 1 && utc[0] === '-' || '0' || '+' || !isNaN(parseFloat(utc[0])))
    {   
        if (utc[0] === '0' && utc.length === 1)
        {   
            let enteredOffset = 0;
            return showDateTime(enteredOffset);
        }
        else if (utc[0] === '+' || !isNaN(parseFloat(utc[0])))
        {
            if (utc.length === 2 && utc[0] === '+')
            {
                // Entered offset
                let enteredOffset = parseFloat(utc[1])*60;
                timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
                return showDateTime(enteredOffset);
            }
            else if (utc.length === 3 && utc[0] === '+')
            {
                // Entered offset
                let enteredOffset = parseFloat(utc[1] + utc[2])*60;
                timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
                return showDateTime(enteredOffset);
            }
            else if (utc.length === 1 && !isNaN(parseFloat(utc[0])))
            {
                // Entered offset
                let enteredOffset = parseFloat(utc[0])*60;
                timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
                return showDateTime(enteredOffset);
            }
            else if (utc.length === 2 && !isNaN(parseFloat(utc[0])))
            {
                // Entered offset
                let enteredOffset = parseFloat(utc[0] + utc[1])*60;
                timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
                return showDateTime(enteredOffset);
            }
            else
            {
                let enteredOffset = 0;
                return showDateTime(enteredOffset);
            }
        }
        else if (utc[0] === '-')
        {
            if (utc.length === 2 && utc[0] === '-')
            {
                // Entered offset
                let enteredOffset = - parseFloat(utc[1])*60;
                timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);   
                return showDateTime(enteredOffset);
            }
            else if (utc.length === 3 && utc[0] === '-')
            {
                // Entered offset
                let enteredOffset = - parseFloat(utc[1] + utc[2])*60;
                timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);   
                return showDateTime(enteredOffset);
            }
            else
            {
                let enteredOffset = 0;
                return showDateTime(enteredOffset);
            }
        }
        else 
        {
            let enteredOffset = 0;
            return showDateTime(enteredOffset);
        }
    }
    else if (utc === '' || !utc || utc === undefined)
    {
        utc = false;
        let enteredOffset = 0;
        return showDateTime(enteredOffset);
    }
    else
    {
        let enteredOffset = 0;
        return showDateTime(enteredOffset);
    }
}

// Function that shows the date and time correctly (format : dd/mm/yyyy - 00:00:00)
function showDateTime(enteredOffset) {
    year    = timeNow.getFullYear();
    month   = ('0'+(timeNow.getMonth()+1)).slice(-2);
    day     = ('0'+timeNow.getDate()).slice(-2);
    hour    = ('0'+timeNow.getHours()).slice(-2);
    minute  = ('0'+timeNow.getMinutes()).slice(-2);
    second  = ('0'+timeNow.getSeconds()).slice(-2);

    showDateTimeValue = day + "/" + month + "/" + year + " - " + hour + ":" + minute + ":" + second;
    timeNow.setMinutes(timeNow.getMinutes() - enteredOffset)

    return showDateTimeValue;
}

// Function which get the shift in seconds between the utc with the API
function timeZone(json) {
    let timeZone = json.timezone / 60 / 60;
    let timeZoneStr = timeZone.toString();
    // console.log("La date et l'heure de " + cityName.split('+').join(' ') + " : " + dateTimeUTC(timeZoneStr));
    console.log(dateTimeUTC(timeZoneStr)); // Shows the correct value I wanted 
    return dateTimeUTC(timeZoneStr); // Shows undefined 
}

// Function that request the openweathermap.org API
function weatherRequest(url) {
    // console.log(url);
    try
    {
        $.getJSON(url, function(json) {
            timeZone(json);
            });
    }
    catch
    {
        console.log("Wrong location.");
    }
}

好了,有人幫我找出錯誤的原因,所以這里是解決方案:由於我們不知道請求何時結束或類似的事情,因此您無法在getJSON之外返回值,因此您需要直接在其中添加所需的內容getJSON有點麻煩,是的,這是main.js中的代碼:

$( "#submit" ).click(function()
{
let  city  =  $('#cityName').val();
let  cityName  =  city.split(' ').join('+');
if(cityName  ===  "")
{
    $('.results').append("<p>Wrong location.</p>");
}
else
{
   weatherRequest("http://api.openweathermap.org/data/2.5/weather?q="  +  cityName  +  "&units=metric&appid=MyAPIkey");
}
});

只需要更改功能weatherRequest:

function  weatherRequest(url) {
// console.log(url);
try
{
    $.getJSON(url, function  callbackSuccess(json) {
let  showDateTimeValue  =  timeZone(json);
let  city  =  json.name;
    $('.results').append("<p>The date and time of "  +  city  +  " : "  +  showDateTimeValue  +  '</p>');
});
}
catch
{
    $('.results').append("<p>Wrong location.</p>");
}
}

希望你能理解,我不好解釋,是的...

暫無
暫無

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

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