<script type="text/javascript">
var s = 'First JavaScript string.';
var c = 'This is second text.'
var colors = new Array("#FF0000","#000000");
for (var i = 0; i < s.length; i++)
document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + s[i] + "</span>");
</script>
How do i include 'c' string in the for loop?
4 Answers 4
You don't need to put single statements in the for loop, you can have how ever many as you want, as long as the centre expression evaluates to a truthy value:
Some examples:
Multiple declarations and a bigger condition:
for(var i = 0, z = 0; i < 100 && z < 100; z++, i++){
console.log(i, z)
}
No incrementation and no declaration:
var i = 0;
for(;i < 100;){
i++;
console.log(i)
}
For your situation I think you want this:
for (var i = 0; i < s.length && i < c.length; i++){
//...do something here
}
This will stop when I is bigger then the length of s or the length of c
Comments
If I understand correctly you need to use a nested loop, although you need to be more specific.
<script type="text/javascript">
var s = 'First JavaScript string.';
var c = 'This is second text.'
var colors = new Array("#FF0000","#000000");
for (var i = 0; i < s.length; i++) {
for (var m = 0; m < c.length; m++) {
... print something in here
}
}
</script>
Comments
for (var i = 0, var j = 0; i < s.length; i++, j--) {
;
}
Comments
Condition should be false, when i is greater/equal to summarized length of s and c.
If i is smaller than length of s, you should write s[i] (with marking), else - write c[i-s.length]. I'd say that ternary operator would fit great here.
cstring in the loop, please explain a bit.