I'm want to loop an array inside and array using JavaScript
outerArray = ["1","2","3","4","5","6","7","8","9","10"];
innerArray = ["val-1","val-2","val-3"];
so that the console logs out:
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
Using:
for (var i = 0; i < outerArray.length; i++) {
console.log(i);
}
Obviously logs: 1,2,3,4,5,.....
However I cant use:
for (var i = 0; i < outerArray.length; i++) {
console.log(i+','+innerArray[i]);
}
As this would give undefined after "val-3" as its a different length to the outer array.
Dave Chen
11k8 gold badges42 silver badges72 bronze badges
-
That's not an outer array, that's simply starting the loop over. Loop up the modulus operator.zzzzBov– zzzzBov2013年09月04日 17:05:07 +00:00Commented Sep 4, 2013 at 17:05
2 Answers 2
You seem to want
console.log(outerArray[i]+','+innerArray[i%innerArray.length]);
answered Sep 4, 2013 at 17:05
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Denys Séguret
@zaf that's why I added a link to the operator's description.
Tore
jsfiddle.net/Pzsyg - also, I think you meant
console.log(outerArray[i]+','+... as the question is askedDenys Séguret
@ToreHanssen Probably, yes.
zaf
@dystroy ah yes, that link on the mozilla developer network explains it all.
outerArray.forEach(function (elem, idx) {
console.log(elem + ", " + innerArray[idx % innerArray.length]);
});
answered Sep 4, 2013 at 17:06
Explosion Pills
192k56 gold badges341 silver badges417 bronze badges
1 Comment
Denys Séguret
Let's precise that forEach isn't compatible with IE8 : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
lang-js