我想弄明白,如何创建一个名为ie的javascript数组。从今天开始的最近7天。
我知道getDay()将返回当天的一些数字,然后我可以将其用作索引来访问包含一周中几天的数组的元素。
这将给我今天的名字,但我需要按时间顺序返回创建一个过去几天的数组我在网上找不到类似于这个问题的任何东西。
任何优雅的解决方案?也许jQuery?
答案 0 :(得分:3)
见jsfiddle:
编辑:将7天存储为变量
http://jsfiddle.net/VDesign/y7ggqzrf/1/
var days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saterday', 'sunday'];
var goBackDays = 7;
$(function() {
var today = new Date();
var daysSorted = [];
for(var i = 0; i < goBackDays; i++)
{
var newDate = new Date(today.setDate(today.getDate() - 1));
daysSorted.push(days[newDate.getDay()]);
}
alert(daysSorted);
});
//output:
//[thursday, wednesday, tuesday, monday, sunday, saterday, friday]
答案 1 :(得分:0)
也许不是最优雅的方式:
var numdays = 7; // Change it to the number of days you need
var d = new Date();
var n = d.getDay();
var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var myArray = new Array(numdays);
for(var i=0;i<numdays;i++){
myArray[i]=weekday[(n-i+numdays)%7];
}
console.log(myArray); // Result: ["Thursday", "Wednesday", "Tuesday", "Monday", "Sunday", "Saturday", "Friday"]
答案 2 :(得分:0)
function myFunction(day) {
var weekday =["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
return weekday[day];
}
var currentDate = new Date().getDay();
var week=[0,1,2,3,4,5,6];
var a=week.splice(currentDate);
var loopWeek=a.concat(week);
var freshWeek=[];
for(var i=0;i<loopWeek.length;i++){
freshWeek.push(myFunction(loopWeek[i]))
}
console.log(freshWeek);