gpt4 book ai didi

javascript - 如何在 JavaScript 中使用循环更改变量值?

转载 作者:行者123 更新时间:2023-12-01 00:05:06 27 4
gpt4 key购买 nike

我有变量 x, x1, y, y1。我想更改变量的值,如下所示:

First time loop run: x= 0, x1=1, y=0, y=1
Second time loop run: x= 0, x1 = 1, y=2, y=3
Third time loop run: x= 2, x1 = 3, y=0, y=1
fourth time loop run: x= 2, x1 = 3, y=2, y=3

谁能帮忙。

var x,x1,y,y1
for(var i=0; i<4; i++){
x = i;
x1 = i+1;
y = i;
y1= i+1;
console.log(x,x1,y,y1);

}

最佳答案

假设您的迭代次数可能不止 4 次,那么使用传统的 for 循环是最简单的:

for (let x = 0; x < 4; x += 2) {
let x1 = x + 1;
for (let y = 0; y < 4; y+= 2) {
let y1 = y + 1;
console.log(x, x1, y, y1);
}
}

另一方面,如果您正好有 4 个循环,则可以预先计算值

let values = [[0, 1], [2, 3]];
for (let [x, x1] of values)
for (let [y, y1] of values)
console.log(x, x1, y, y1);

将此方法扩展到更多迭代:

let n = 4;
let values = [...Array(n)].map((_, i) => [i * 2, i * 2 + 1]);
for (let [x, x1] of values)
for (let [y, y1] of values)
console.log(x, x1, y, y1);

关于javascript - 如何在 JavaScript 中使用循环更改变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60439111/

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