I am writing next_previous() function for pagination purpose, I have for loop which is moving from 0 to the given length. I want to use the same loop for two cases from 0 to 10 and from 10 to 0.
for (var i = 0; i < 10; i++) {
}
for (var i = 10; i > 0; i--) {
}
to use both cases in one loop I am doing something like this but not working
var i = 0; a = '', b = '';
if(somevar === true){
i = 0 , a = '++', var b = '<';
}else{
i = 10 , a = '--', var b = '>';
}
for (i; i +b+ 0; i+a) {
}
now problem is javascript not allowing concatenation this way, how can I achieve this?
See screenshot
Try this approach which uses for the logic part ( increment and condition ) functions.
ES6
let i = 0;
let a;
let b;
let count = 0;
let somevar = true;
if(somevar) {
i = 0;
count = 10;
a = () => i++;
b = () => i < count;
} else {
i = 10;
count = 0;
a = () => i--;
b = () => i > count;
}
for (; b(); a()) {
console.log(i);
}
ES5
var i = 0;
var a;
var b;
var count = 0;
var somevar = true;
if(somevar) {
i = 0;
count = 10;
a = function() { i++; };
b = function() { return i < count; };
} else {
i = 10;
count = 0;
a = function() { i--; };
b = function() { return i > count; };
}
for (; b(); a()) {
console.log(i);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With