【问题标题】:Problem to integrate the function to transform Kelvin in Celsius集成将开尔文转换为摄氏温度的函数的问题
【发布时间】:2021-03-19 17:25:49
【问题描述】:

我在集成将开尔文转换为摄氏温度的函数时遇到问题,有人可以帮忙吗?我对这个世界很陌生,善良! :)

我该怎么做才能将它转换成摄氏度?

let key = ...........

let requestCity = async (city) => {
    let url = 'https://api.openweathermap.org/data/2.5/weather'
    let query = '?q=' + city + '&appid=' + key;
    let response = await fetch(url + query);
    let data = await response.json();
    return data;
}

let searchForm = document.querySelector('.search-location');
let cityValue = document.querySelector('.search-location input');
let cityName = document.querySelector('.city-name p');
let condition = document.querySelector('.condition');
let temp = document.querySelector('.temp')
let high = document.querySelector('.high')
let low = document.querySelector('.low')
let hum = document.querySelector('.hum')
let feel = document.querySelector('.feel')
// let celsius = (kelvin) => {
//     celsius = math.round(kelvin - 273.15);
//     return celsius
// }
updateWeather = (city) => {
    cityName.textContent = city.name;
    condition.innerHTML = city.weather[0].description;
    temp.innerHTML = city.main.temp + '°K';
    high.innerHTML = city.main.temp_max + '°K'
    low.innerHTML = city.main.temp_min + '°K'
    hum.innerHTML = city.main.humidity + '%'
    feel.innerHTML = city.main.feels_like + '°K'

}

searchForm.addEventListener('submit', (event) => {
    event.preventDefault();
    let citySearched = cityValue.value;
    console.log(citySearched);
    searchForm.reset();
    requestCity(citySearched)
        .then((data) => { updateWeather(data) })
        .catch((error) => { console.log(error) })

})

【问题讨论】:

    标签: javascript function transform openweathermap


    【解决方案1】:

    有一个公式可以将开尔文转换为摄氏度(基本上只需从开尔文度数中减去 273.15 即可得到对应的摄氏度数)。

    这是我写的一小段代码,你可以理解:

    function toCelsius(kelvin) {
        if(Number.isFinite(kelvin)) { // Checking if kelvin is a number.
            const KELVIN_CELSIUS_DIFF = 273.15; // maybe unnecessary here, but it is good practice to avoid magic numbers.
            let celsius = kelvin - KELVIN_CELSIUS_DIFF;
            return celsius; // could also be just return kelvin - KELVIN_CELSIUS_DIFF;
        } else {
            // kelvin is not a number, should be handled.
        }
    }
    

    【讨论】:

    • 谢谢,反正我的问题还不清楚。我在 updateWeather 中集成 toCelsius 函数时遇到问题..... innerHTML .....
    • 您不必为此任务在开尔文和摄氏度之间进行转换,您只需在 API 调用中添加“&units=metric”或“&units=kelvin”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2021-11-13
    • 2023-02-24
    • 2017-09-25
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    相关资源
    最近更新 更多