[英]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? 如何在for循环中包含“ c”字符串?
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: 您不需要将单个语句放入for循环中,只要中心表达式的计算结果为真实值,就可以有任意数量的语句:
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
当我大于
s
的长度或c
的长度时,这将停止
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>
Condition should be false, when i
is greater/equal to summarized length of s
and c
. 当
i
大于/等于s
和c
总结长度时,条件应该为假。
If i
is smaller than length of s
, you should write s[i]
(with marking), else - write c[is.length]
. 如果
i
小于s
长度,则应写s[i]
(带有标记),否则应写c[is.length]
。 I'd say that ternary operator would fit great here. 我想说三元运算符非常适合这里。
for (var i = 0, var j = 0; i < s.length; i++, j--) {
;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.