间隔:每个阵列30个循环

时间:2015-04-29 09:41:23

标签: javascript

在Javascript中,如果是<=4返回数据数组,那么如何进行循环:

["0:00", "0:30", "1:00", "1:30", "2:00", "2:30", "3:30", "4:00"]

这是例如间隔时间“:30”。

示例:

for (var i=0; i<=4; i++) {
  a[i] = i.toString() + ":00";
  a[i+1] = i.toString() + ":30";
}

3 个答案:

答案 0 :(得分:1)

var arr = [];
var j = 0;
for (var i = 0 ; i < 4; i++) {
  arr[j] = i.toString() + ":00";
  if (j < 4)
    arr[j+1] = i.toString() + ":30";
  j += 2;
}

答案 1 :(得分:0)

您的代码创建

["0:00", "0:30", "1:00", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30"]

所以你只想排除最后一步?

var maxhour = 4
for (var i=0; i<(2*maxhour); i+=2) {
  a[i] = i.toString() + ":00";
  if(i<maxhour)
     a[i+1] = i.toString() + ":30";
}

答案 2 :(得分:-1)

for (var i=0; i<=4; i++) 
{
  a[2 * i]     = i + ":00";
  a[2 * i + 1] = i + ":30";
}  

但此解决方案将包含04:30

要解决此问题,您可以使用下一个代码:

for (var i=0; i<=8; i++) 
{
  var prefix = i % 2 == 0 ? ":00" : ":30";
  a[i] = Math.floor(i / 2) + prefix;
}