简体   繁体   中英

Get data about the position of our sun through a function. How?

I am using mourner/suncalc to get information about our sun. I want to get all the times where the position of our sun will be, using SunCalc.getTimes() , but to prevent using "miles long" variables, I want to call each data through a function.

I am thinking about something like this:

function sun_times(string) {
    var sun_times = SunCalc.getTimes(new Date(), 54.528486, -7.569268);
    return (sun_times.string.getHours().toString() < 10 ? '0' + sun_times.string.getHours().toString() : sun_times.string.getHours().toString());
}

console.log(sun_times('dawn'));

This example returns (as expected) TypeError: sun_times.string is undefined .

Instead of entering sun_times.dawn.getHours().toString() + ':' + sun_times.dawn.getMinutes().toString() for every time at dawn, dusk, golden hour, nadir, nautical dawn, and so on, I just want to enter the function and then the data I want to print out, for an example sun_times('dawn') .

How can I accomplish this the best way?

A JavaScript object works like a dictionary structure. We use the [] indexing operator to access properties only known at runtime. It's like array access, but with strings instead of numbers.

function sun_times(string) {
    var sun_times = SunCalc.getTimes(new Date(), 54.528486, -7.569268);
    return (sun_times[string].getHours().toString() < 10 ? '0' + sun_times[string].getHours().toString() : sun_times[string].getHours().toString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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