user3017513
user3017513

Reputation: 1450

javascript for function - How do i include another condition in the for loop

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

Upvotes: 1

Views: 147

Answers (4)

Filip Malczak
Filip Malczak

Reputation: 3194

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.

Upvotes: 0

FabianCook
FabianCook

Reputation: 20557

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

Upvotes: 2

crafter
crafter

Reputation: 6296

for (var i = 0, var j = 0; i < s.length; i++, j--) {
   ;
}

Upvotes: 0

jtromans
jtromans

Reputation: 4263

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>

Upvotes: 0

Related Questions