gpt4 book ai didi

javascript - js中的双向循环

转载 作者:行者123 更新时间:2023-11-29 10:09:09 25 4
gpt4 key购买 nike

我需要收到这样的东西:

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

也许有人遇到过这种麻烦?

最佳答案

给你:

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/

关于javascript - js中的双向循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36841478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com