如何使用javascript获得学年

时间:2017-11-06 11:02:34

标签: javascript

var year = new Date().getFullYear();
var lastyear = new Date().getFullYear()-1;
var range = [];
var lastrange = [];
lastrange.push(lastyear);
range.push(year);
  for (var i = 1; i < 7; i++) 
  {
    lastrange.push(lastyear + i);
    range.push(year + i);
    var fullyear = lastrange.concat(range);
   }
$scope.years = fullyear;

如何以2017-18,2018-19这样的学年为止。 请帮助。

先谢谢

2 个答案:

答案 0 :(得分:2)

我正在使用一个新的String数组

  

var academicYear = [];

将在执行循环期间填充

academicYear.push(lastrange[i-1]+"-"+(lastrange[i]).toString().slice(-2));// 2016-17

这是一个工作样本..

&#13;
&#13;
var year = new Date().getFullYear();
var lastyear = new Date().getFullYear()-1;
var range = [];
var lastrange = [];
var academicYear=[];
lastrange.push(lastyear);
range.push(year);
  for (var i = 1; i < 7; i++) 
  {
    lastrange.push(lastyear + i);    
    range.push(year + i);
    academicYear.push(lastrange[i-1]+"-"+(lastrange[i]).toString().slice(-2));
    var fullyear = lastrange.concat(range);
   }
console.log(academicYear);  
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以遍历fullyear并检查下一个项目是否存在。 取下一个项目的最后两个字符,并用-附加它们。

例如:

var result = [];
for (var i = 0; i < fullyear.length; i++) {
    if (fullyear[i + 1]) {
        var academicYear = fullyear[i] + "-" + fullyear[i + 1].toString().slice(-2);
        result.push(academicYear);
    }
}
console.log(result.join());

这将导致:

2016-17,2017-18,2018-19,2019-20,2020-21,2021-22,2022-17,2017-18,2018-19,2019-20,2020-21,2021-22,2022-23