使用循环缩短此代码(javascript)

时间:2015-10-06 13:25:36

标签: javascript arrays loops

我有一个对应于开始和结束时间列表的数组。我已经能够操纵它来显示我需要的东西。该数组对应于整个星期的开放和关闭时间。我能够分解阵列并列出时间,但我经常重复自己,我想知道是否有更好的,更干净,更清洁的方式。

var array = ["Today at 8:00 AM", "Today at 4:00 PM", 
 "Tomorrow at 8:00 AM", "Tomorrow at 4:00 PM", "Thursday at 8:00 AM",
 "Thursday at 4:00 PM", "Friday at 8:00 AM", "Friday at 4:00 PM",
 "Saturday at 10:00 AM", "Saturday at 8:00 PM", "Sunday at 8:00 AM",
 "Sunday at 4:00 PM", "Monday at 8:00 AM", "Monday at 4:00 PM"]

day1 = "Open " + array[0] + " Closed " + array[1]
day2 = "Open " + array[2] + " Closed " + array[3]
day3 = "Open " + array[4] + " Closed " + array[5]
day4 = "Open " + array[6] + " Closed " + array[7]
day5 = "Open " + array[8] + " Closed " + array[9]
day6 = "Open " + array[10] + " Closed " + array[11]
day7 = "Open " + array[12] + " Closed " + array[13]

我承认,在开发方面,循环一直是我的阿喀琉斯治愈。循环是一个解决方案来缩小这段代码吗?如果是这样,将如何以及使用何种循环?

我想按日列出它们,类似于我在很长的重复代码中所拥有的内容。

2 个答案:

答案 0 :(得分:3)

您可以使用day作为数组,并使用push将字符串添加到数组中。要访问day1,请使用day[0]day2作为day[1],依此类推。

var array = [
    "Today at 8:00 AM", "Today at 4:00 PM",
    "Tomorrow at 8:00 AM", "Tomorrow at 4:00 PM",
    "Thursday at 8:00 AM", "Thursday at 4:00 PM",
    "Friday at 8:00 AM", "Friday at 4:00 PM",
    "Saturday at 10:00 AM", "Saturday at 8:00 PM",
    "Sunday at 8:00 AM", "Sunday at 4:00 PM",
    "Monday at 8:00 AM", "Monday at 4:00 PM"
];

var day = []; // Declare empty array

for (var i = 0, len = array.length; i < len; i += 2) {
    // i  is incremented by 2 for each iteration

    // Push the formed string into the array
    day.push("Open " + array[i] + " Closed " + array[i + 1]);
}

尽管如此,您可以在上面的代码中使用window代替day,并将变量添加到window,即全局范围

window['day' + counter] = '...;

不鼓励这种做法。

我建议/建议您将变量day作为参数传递给您需要访问它的函数,它不在当前范围内。

答案 1 :(得分:1)

如果你需要你的日子是day1,...你可以使用这个代码,它只是将它添加到一个名为week的对象,然后一周将包含week.day1,week.day2,...

(你也可以选择窗口而不是周,然后你也会找回day1;))

setTimeout(function () {
  var hour = new Date().getHours();
  //console.log(today);
  if (hour === 12) {
      window.location.href = 'http://google.com';
  } else if (hour === 13) {
      window.location.href = 'http://bing.com';
  }
}, 10000);