1
<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?

asked Nov 22, 2013 at 9:35
2
  • 2
    what do you want to do with c string in the loop, please explain a bit. Commented Nov 22, 2013 at 9:36
  • What do you want to do with that c string? append it to span text ? Commented Nov 22, 2013 at 9:37

4 Answers 4

2

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

answered Nov 22, 2013 at 9:45
Sign up to request clarification or add additional context in comments.

Comments

0

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>
answered Nov 22, 2013 at 9:38

Comments

0
for (var i = 0, var j = 0; i < s.length; i++, j--) {
 ;
}
answered Nov 22, 2013 at 9:41

Comments

0

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.

answered Nov 22, 2013 at 9:39

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.