What does this sample code do?

I found this example on jetbrains.com

async function getWeather(cityid: number){
    var weather = await getForecast(cityid);
    var {t: temperature, h: humidity} = weather;
    return { temperature, humidity};
}

I understand async / await, but I'm trying to figure out what happens with the last two lines.

var {t: temperature, h: humidity} = weather;

As far as I can tell, this creates a var with two properties, t type temperature and h type humidity.

return { temperature, humidity};

It seems to me that it returns a new object with two child objects, temperature and humidity. I do not understand how this is obtained from the weather object.

I don't know if this is a javascript question or typescript question, so I am tagged as both.

+4
source share
2 answers

var {t: temperature, h: humidity} = weather;

. : https://basarat.gitbooks.io/typescript/content/docs/destructuring.html

, weather.t temprature weather.h humidity

return {, };

temprature humidity. : return { temperature:temperature, humidity:humidity};. ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

+5

var {t: temperature, h: humidity} = weather; - ES6, destructing.

, weather { t: 60, h: 20 }. , weather , - :

var temperature = weather.temperature;
var humidity = weather.humidity; 

, .

var {t: temperature, h: humidity} = weather;
console.log(temperature); // 60
console.log(humidity); // 20

temperature humidity .

, "" , "" . weather :

var {t: t, h: h} = weather;
console.log(t); // 60
console.log(h); // 60

:

var {t, h} = weather;
console.log(t); // 60
console.log(h); // 60
+4

Source: https://habr.com/ru/post/1612666/


All Articles