使用JavaScript打印数字模式-同一循环中的升序和降序 [英] Print number patterns in JavaScript - Ascending and Descending in same loop

查看:51
本文介绍了使用JavaScript打印数字模式-同一循环中的升序和降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按以下方式打印数字,如果条件在for循环中,则我只需要使用一个for循环打印即可.

如果我给s = 7,则输出模式将为0,1,2,3,4,5,6,7,6,5,4,3,2,1,0

这是我尝试但未成功的方法.

  for(x = s,step = -b,i = 0; x< = s; step = x + step< = 0?-step:step,x + = step,i ++,step){console.log(x,i,step)} 

我已经用不同的模式问了这个降序的问题,这也是一个不同的问题,这就是我创建另一个问题的原因

在JavaScript中打印数字模式

我不想使用任何预先构建的库来实现此目的,例如Math.abs()

解决方案

 函数printNumbers(s){for(i = 0,num = 0; i< = s * 2; ++ i< = s?num ++:num-){console.log(num);}}printNumbers(7);  

具有步骤支持的自上而下版本:

 函数printNumbers(s,step){for(i = 0,num = s; num< = s; i + = step,i <= s?num-= step:num + = step){console.log(num);}}printNumbers(7,2);  

您可以按照不同的步骤进行尝试.

I want to print numbers in pattern as below also I need this to print using only one for loop not in if condition inside for loop.

If I give s = 7 the output pattern would be 0,1,2,3,4,5,6,7,6,5,4,3,2,1,0

This is what I tried but not successful.

for (x = s, step = -b, i = 0; x <= s; step = x + step <= 0 ? -step : step, x += step, i++, step) {
    console.log(x, i, step)
}

I've already asked a question for this descending order with a different pattern also this is a different question that's the reason I created another question

Print number patterns in JavaScript

I don't want to use any pre-built libraries to achieve this such as Math.abs()

解决方案

function printNumbers(s){
   for (i = 0, num = 0; i <= s * 2; ++i <= s ? num++ : num--){
       console.log(num);
   }
}

printNumbers(7);

Top down version with steps support:

function printNumbers(s, step){
   for (i = 0, num = s; num <= s; i+= step, i <= s ? num -= step : num += step) {
       console.log(num);
   }
}

printNumbers(7, 2);

You can try it with different steps.

这篇关于使用JavaScript打印数字模式-同一循环中的升序和降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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