如何在for / in函数中重复两次对象属性循环

时间:2017-12-04 01:57:08

标签: javascript javascript-objects

如何在for / in循环中重复两次'times'对象?

var times = []
, periods = ['am', 'pm']
, hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
, prop = null
, hour = null;

for (prop in periods) {
for (hour in hours) {
  times.push(('' + hours[hour]) + ':' + '00' + periods[prop]);
}

} // object properties from 12:00am to 11:00pm

所以我希望输出是[12:00 am .... 11:00 pm(第一次循环)... 12:00 am ... 11:00 pm(第二次循环)。有什么想法吗?谢谢

2 个答案:

答案 0 :(得分:0)

构建两个数组并concatenate

var times1 = []
, times2 = []
, times = []
, periods = ['am', 'pm']
, hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
, prop = null
, hour = null;

for (prop in periods) {
for (hour in hours) {
  times1.push(('' + hours[hour]) + ':' + '00' + periods[prop]);
  times2.push(('' + hours[hour]) + ':' + '00' + periods[prop]);
}

} // object properties from 12:00am to 11:00pm

times = times1.concat(times2);

答案 1 :(得分:-2)

尝试使用* 2功能,如果不起作用,则使变量的重复次数增加一倍。

在其他2个循环周围添加此循环,看看是否有效。

for(2){

}