简体   繁体   English

JavaScript-Console.log返回一些内容,但返回时显示未定义

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

the problem as the title said : The console.log show the correct value but when I return it and show it with the DOM by adding a paragraph (using jQuery) in the paragraph it shows undefined... 标题中提到的问题:console.log显示正确的值,但是当我返回该值并通过在段落中添加一个段落(使用jQuery)将其与DOM一起显示时,它显示未定义...

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

return  dateTimeUTC(timeZoneStr); 
// Shows undefined

So what I want to do : A form with html with a simple input text and a submit button, when the submit button is click so it saves the text of the input in a variable using jQuery : let variable = $('#cityName').val(); 因此,我想做的是:使用带有简单输入文本和提交按钮的html表单,单击提交按钮时,它将使用jQuery将输入的文本保存在变量中: let variable = $('#cityName').val(); (the value should be a city name) because when I've got the city name value I ask the openweathermap API to send me the json and to give the value of the timezone in ms then I need to convert the ms value in hour so for example New York, : timezone: -14400 ( json.timezone / 60 / 60) so the result with New york is UTC - 4, then I have a script that convert my UTC thing in an real date time but that script work so I don't need to explain you... when that function finish it gives me the result like that : (该值应为城市名称),因为当我获得城市名称值时,我要求openweathermap API向我发送json并以ms为单位提供时区的值,那么我需要将ms值转换为小时,因此例如纽约,:时区:-14400( json.timezone / 60 / 60)因此纽约的结果是UTC-4,那么我有一个脚本可以将我的UTC事物转换为实际日期时间,但是该脚本可以正常工作我不需要向您解释...当该函数完成时,它会给我这样的结果:

Tue Aug 13 2019 05:53:39 GMT+0200 Not really good for presentation so then I made a function that convert this in a better way : 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;

Then this return value go where I executed the function so in the function called timeZone and it's there that I've got the console.log working but with return it shows undefined. 然后,此返回值到达我执行该函数的位置,因此在名为timeZone的函数中,在那里我已经使console.log工作,但返回时它显示未定义。

Hopefully, I explained well and you'll understand what I'm trying to do, if anyone can give me some help ^_^ 希望我能解释得很好,如果有人可以给我一些帮助,您会明白我正在尝试做的事情^ _ ^

EDIT - FULL CODE : 编辑-完整代码:

Index.html code : 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 code : 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 code : 功能码:

/* 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.");
    }
}

Alright somebody help me to find out why it was wrong so here is the solution : Since we can't know when a request ended or such, you can't return value outside the getJSON, you need to append the things you want directly in the getJSON thingy so yeah here is the code in main.js : 好了,有人帮我找出错误的原因,所以这里是解决方案:由于我们不知道请求何时结束或类似的事情,因此您无法在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");
}
});

Only need to change the function weatherRequest : 只需要更改功能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>");
}
}

Hopefully you understood, i'm bad for explaining so yeah... 希望你能理解,我不好解释,是的...

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

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