繁体   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