动态改变循环的方向 [英] alter the direction of loop dynamically

查看:61
本文介绍了动态改变循环的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为两个整数之间的接近行为提出一种算法。基本上,给定两个整数, a b ,我想要 a 接近 b ,即使 b 小于 a 。我认为这应该是循环增量函数的交换方式:

I am trying to come up with an algorithm for an "approaching" behavior between two integers. Basically, given two integers, a and b, i want a to "approach" b, even if b is less than a. The way i think this should look is a swapping of the loop incrementer function:

for (var i = a; approachCond(i, a, b); approachDir(i,a, b)) {
   // some fn(a, b);
}

其中

approachCond(i, a, b) {
 return a < b ? i < b :  i > b;
}

approachDir(i, a, b) {
 return a < b ? i++ : i--
}

然而,当我尝试这样做时,浏览器会冻结(铬)。有谁知道如何动态改变循环的方向?

However, when i try doing this the browser freezes (Chrome). Does anyone know how to dynamically alter the direction of a loop?

推荐答案

我认为如果你只是使用它会更清楚一点a 循环:

I think it's a little clearer to read if you just use a while loop:

'use strict';
let a = 12, b = 6;

let i = a;

while (i !== b) {
  console.log(i);
  i += a < b ? 1 : -1;
}

我甚至离开了可爱的三元组这些天人们似乎如此反对if语句。

I even left the cute ternary since people seem so opposed to if-statements these days.

这篇关于动态改变循环的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆