循环数组内部和数组

时间:2013-09-04 17:03:32

标签: javascript arrays

我想使用JavaScript将数组内部和数组循环

outerArray = ["1","2","3","4","5","6","7","8","9","10"];
innerArray = ["val-1","val-2","val-3"];

以便控制台注销:

1,val-1
2,val-2
3,val-3
4,val-1
5,val-2
6,val-3
7,val-1
8,val-2
9,val-3
10,val-1

使用:

for (var i = 0; i < outerArray.length; i++) {
    console.log(i);
}

显然是日志: 1,2,3,4,5,.....

但是我无法使用:

for (var i = 0; i < outerArray.length; i++) {
    console.log(i+','+innerArray[i]);
}

因为这会在“val-3”之后给出 undefined ,因为它与外部数组的长度不同。

2 个答案:

答案 0 :(得分:3)

你似乎想要

console.log(outerArray[i]+','+innerArray[i%innerArray.length]);

Reference on the % operator

答案 1 :(得分:0)

outerArray.forEach(function (elem, idx) {
    console.log(elem + ", " + innerArray[idx % innerArray.length]);
});

http://jsfiddle.net/bh4bs/