嵌套循环:在循环中实现循环?

时间:2015-10-10 20:07:15

标签: javascript loops

所以我必须使用以下数组来制作本周的每日计划器:

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

activities = ["grump", "teach", "hype", "sleep"];

对于每件事,我想知道当天的数字,并希望控制台中的输出看起来像这样:(星期一的活动从1开始)

=> Monday
=> grump1
=> teach1
=> hype1
=> sleep1
=> Tuesday
=> grump2
=> teach2
=> hype2
=> sleep2
=> Wednesday

所以我假设我必须在循环中实现一个循环,但我对如何处理这个问题毫无头绪。我是从for循环开始的吗?请帮忙。

1 个答案:

答案 0 :(得分:3)

你想要做的是forEach:

days.forEach(function(day, i) { //forEach day in days
    console.log(day);
    activities.forEach(function(thing) {
        console.log(thing + (i + 1)); //+ 1 because array indicies start 0
    });
});