簡體   English   中英

通過函數獲取有關太陽位置的數據。 怎么樣?

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

我正在使用mourner / suncalc獲取有關太陽的信息。 我想使用SunCalc.getTimes()獲得所有太陽位置的時間,但是為了防止使用“英里長”變量,我想通過一個函數調用每個數據。

我在想這樣的事情:

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'));

本示例返回(按預期方式) TypeError: sun_times.string is undefined

而不是每次在黎明,黃昏,黃金時段,最低點,航海黎明等時間輸入sun_times.dawn.getHours().toString() + ':' + sun_times.dawn.getMinutes().toString()來代替,我只想輸入函數,然后輸入要打印的數據,例如sun_times('dawn')

我怎樣才能最好地做到這一點?

JavaScript對象的工作方式類似於字典結構。 我們使用[]索引運算符訪問僅在運行時已知的屬性。 就像數組訪問一樣,但是使用字符串而不是數字。

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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM