Basilin Joe
Basilin Joe

Reputation: 702

Multi variable for loop Java Script

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]);
}

Upvotes: 0

Views: 52

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

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]);
}

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68383

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]);
}

Upvotes: 0

Related Questions