Nikita Sviridenko Nikita Sviridenko - 1 month ago 8
Javascript Question

Two-sided loop in js

I need to receive something like this:

a
b
c
d
c
b
a
b
c
d
c
b
a
...


I've created a code that solves it, but partially:

var matrix = ['a', 'b', 'c', 'd'];

for (var i = 0; i < 20; i ++) {
var period = Math.ceil((i + 1) / matrix.length);
var offset = i % matrix.length;

if (period % 2 === 0) {
console.log(period, offset, matrix[matrix.length - offset - 1]);
} else {
console.log(period, offset, matrix[offset]);
}
}


and a response is:

1 0 "a"
1 1 "b"
1 2 "c"
1 3 "d"
2 0 "d"
2 1 "c"
2 2 "b"
2 3 "a"
3 0 "a"
...


Maybe somebody has an experience with this trouble?

Answer

Here you go:

var matrix = ["a", "b", "c", "d"];
var length = 20;

for (var i = 0, a = 0, e = 1; i < length; a += e) {
    if(a >= matrix.length - 1 || a <= 0 && i++ != 0) e *= -1;
    console.log(matrix[a]);
}

JSFiddle: https://jsfiddle.net/p9102usd/