js中的双边循环

时间:2016-04-25 13:05:34

标签: javascript loops

我需要收到这样的内容:

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

我已经创建了一个解决它的代码,但部分是:

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

并且回复是:

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"
...

也许有人有这种麻烦的经验?

3 个答案:

答案 0 :(得分:3)

你走了:

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/

答案 1 :(得分:1)

对指数进行修正的解决方案。

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

for (i = 0; i < 20; i++) {
    index = i % (matrix.length * 2 - 2);
    if (index >= matrix.length) {
        index = matrix.length * 2 - 2 - index;
    }
    document.write(matrix[index] + '<br>');
}

答案 2 :(得分:0)

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) {
        if (offset === 0) {
            continue;
        } else {
            console.log(period, offset, matrix[matrix.length - offset - 1]);
        }
    } else {
        if (period != 1 && offset === 0) {
            continue;
        } else {
            console.log(period, offset, matrix[offset]);
        }
    }
}