我希望文本每天都根据日期更改。
文本是自行车的位置。我知道未来 3 个月的自行车会在哪里。
但是有90天,90个名额。实施这一点的最有效方法是什么?
我知道我可以写很多"elseif"条件,但我认为有一种更有效的方法可以做到这一点。
请问您有什么想法吗?
if 条件如下所示(我认为(:
var date = new Date();
var day = date.getDate();
var n = date.getMonth();
var place;
if (day === 1 && n === 1) {
place = "Name of the city";
}
elseif(day === 2 && n === 1) {
place = "Name of Another City!"
}
document.getElementById("CityName").innerHTML = place;
这需要编写与天数一样多的条件。也许我可以使用 json?
你觉得怎么样?
只需使用一个对象:
const locations = {
"2019-01-01": "Berlin",
"2019-01-02": "Amsterdam",
...
"2019-03-12": "New York",
};
然后,您可以访问带有日期的城市 locations['2019-01-02']
特别location[myDate]
.
如果你有一个像const today = new Date()
这样的date
变量,你可以使用.toISOString().substr(0, 10)
来获取该格式:
console.log(locations[today.toISOString().substr(0, 10)]);
Yo 可以使用包含所有城市的数组和一个获取值的函数来做到这一点。
像这样:
var places = [
"Name of the city",
"Name of Another City!",
"Another city..."
];
function getPlaceName(day) {
var index = day - 1;//day 1 = index 0
return places[index];
}
var date = new Date();
var day = date.getDate();
var n = date.getMonth();
var place = getPlaceName(day);
document.getElementById("CityName").innerHTML = place;
您可以像这样构建数据:
const bikeLocations = [{
rangeStart: new Date(2018, 3, 1),
rangeEnd: new Date(2018, 6, 1),
location: 'city 1'
}, {
rangeStart: new Date(2018, 6, 1),
rangeEnd: new Date(2018, 9, 1),
location: 'city 2'
}, ...]
并获取当前位置:
const now = new Date()
console.log(bikeLocations.filter(bikeLocation => bikeLocation.rangeStart < now && bikeLocation.rangeEnd > now)[0])
<</div>
div class="one_answers"> 当然,您可以创建一个 JSON,但另一种方便的方法是使用您拥有的所有值定义一个常量data
:
// first number is day, second is month
const data = {
'1-1': 'city #1',
'22-3': 'city #2',
'3-1': 'city #3'
}
然后创建函数getCity
:
const getCity = (day, month) => data[`${day}-${month}`]
最后只需用日和月的参数调用getCity
:
const day = new Date().getDate()
const month = new Date().getMonth()
const place = getCity(day, month)
鉴于您设置数据的方式,我会基于 day
和 n
构建一个对象。这样,您可以拥有类似以下内容:
var places = {
1: {
1: 'New York',
2: 'Philadelphia'
/* ... */
},
2: {
1: 'Washington'
}
}
然后你可以得到你的名字,就像这样:
var todaysPlace = places[n][day];
但老实说,我更喜欢其他一些答案,比如有一个日期字符串的对象。