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

时间:2019-08-13 10:06:37

标签: javascript return console.log

标题中提到的问题: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事物转换为实时日期,但是该脚本可以工作,所以我不需要向您解释...函数完成后,它会给我这样的结果:

  

2019年8月13日星期二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.");
    }
}

1 个答案:

答案 0 :(得分:0)

好的,有人可以帮助我找出错误的原因,所以这里是解决方案: 由于我们无法确定请求何时结束,因此您无法在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>");
}
}

希望您能理解,我不好解释,是的...

相关问题