gpt4 book ai didi

javascript - 具有不对称增量的循环

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:10 24 4
gpt4 key购买 nike

我在这里尝试做的是使用一个循环函数,该函数将不对称地递增一个数字并在每次迭代时返回它。

  • 我会从 11 开始。
  • 我会增加 2 得到 13,
  • 增加 4 得到 17,
  • 增加 2 得到 19,
  • 增加 2 得到 21,
  • 增加 2 得到 23,
  • 增加 4 ....

增量的模式将是循环的并随时间重复:2, 4, 2, 2, 2, 4, 2, 2, 2, 4, 2, 2, 2, 4, 2, 2 , 2, 4 等等。

我一直在考虑 for 和 while 循环、生成器函数或 Array.prototype.reduce,但似乎无法找到解决我的问题的简单方法。

关于我应该如何继续,我还没有想出任何好的起点......下面是我希望它如何将值推送到数组的示例,但它们也可以仅由函数返回...

function returnNums(maxValue) {
let returnedNums = [];
for (let i = 11; i <= maxValue;) {
returnedNums.push(i);
// magical solution to increment i following my desired pattern right here
}
}

最佳答案

您可以添加一个 j 变量来遍历 [2, 4, 2, 2] 数组并将 i 递增 arr[j % arr.length]

let arr = [2, 4, 2, 2];

function returnNums(maxValue) {
let returnedNums = [];

for (let i = 11, j = 0; i <= maxValue; j++) {
returnedNums.push(i);
// increment i following my desired pattern right here
i += arr[j % arr.length];
}
return returnedNums;
}

console.log(returnNums(20));
console.log(returnNums(50));

关于javascript - 具有不对称增量的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57708000/

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