Is there any way, below code works properly.. i want 'i' to stop when the limit is reached .. without using an if condition
var a1 = [1, 2, 3, 4, 5, 6];
var a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = 0; i < a1.length, j < a2.length; i++, j++) {
console.log('a1: ' + '[' + i + ']' + a1[i]);
console.log('a2: ' + a2[j]);
}
asked Dec 3, 2015 at 7:16
-
is there any special reason for using two counters with the same content?Nina Scholz– Nina Scholz2015年12月03日 08:44:29 +00:00Commented Dec 3, 2015 at 8:44
-
No special reasons,other than am lazyBasilin Joe– Basilin Joe2015年12月03日 10:05:34 +00:00Commented Dec 3, 2015 at 10:05
2 Answers 2
The second parameter of a loop should be a boolean condition.
This one
i < a1.length, j < a2.length
is actually interpreted in such way that it returns the result of i < a1.length
only.
Since you want the loop to execute while both of conditions are true, combine these conditions using logical AND operator:
var a1 = [1, 2, 3, 4, 5, 6];
var a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = 0; i < a1.length && j < a2.length; i++, j++) {
console.log('a1: ' + '[' + i + ']' + a1[i]);
console.log('a2: ' + a2[j]);
}
By the way, i
and j
are actually duplicating each other. You may use the single loop counter:
var a1 = [1, 2, 3, 4, 5, 6];
var a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0; i < a1.length && i < a2.length; i++) {
console.log('a1: ' + '[' + i + ']' + a1[i]);
console.log('a2: ' + a2[i]);
}
or even
var a1 = [1, 2, 3, 4, 5, 6];
var a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var minLength = Math.min(a1.length, a2.length);
for (var i = 0; i < minLength; i++) {
console.log('a1: ' + '[' + i + ']' + a1[i]);
console.log('a2: ' + a2[i]);
}
answered Dec 3, 2015 at 7:19
2 Comments
Basilin Joe
Thing is ,i need ' j ' to go till 10
Yeldar Kurmangaliyev
@CodeBean There is no convenient and proper way to do this using
for
loop without if
condition. Moreover, there is not so much sense. However, you may implement it using while
.no need for if condition
var a1 = [1, 2, 3, 4, 5, 6];
var a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = 0; i < a1.length, j < a2.length, a1[i]; i++, j++) {
console.log('a1: ' + '[' + i + ']' + a1[i]);
console.log('a2: ' + a2[j]);
}
answered Dec 3, 2015 at 7:19
Comments
lang-js