0

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
2
  • is there any special reason for using two counters with the same content? Commented Dec 3, 2015 at 8:44
  • No special reasons,other than am lazy Commented Dec 3, 2015 at 10:05

2 Answers 2

1

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

Thing is ,i need ' j ' to go till 10
@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.
0

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

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.