Print number patterns in JavaScript

天大地大妈咪最大 提交于 2021-01-28 08:00:43

问题


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 7, 5, 3, 1, 3, 5, 7

If s=6 then output is 6, 4, 2, 4, 6

This is what I tried but not successful.

const s = 7, b = 2

for (x = s, d = b; x > 0 && x <= 7; x -= 2) {
  console.log(x)
}

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


回答1:


With ternary operator:

const s = 10, b = 2

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



回答2:


var s = 7, b = 2, x, d;
var front = " ", back = " ";

for (x = s, d = b; x - b > 0 ; x -= b) {
    front = front + " " + x; 
    back = x + " " + back;
}
console.log(front + " " + x + " " + back);



回答3:


This works for both even and odd numbers:

const s = 8, b = 2

for (x=s,step = b; x <=s ; (x===1 || x===2) ? (step = -b, x = x-step ): x= x-step) {
    console.log(x)
}

What I have done is that in the increment/ decrement block when x equals to 1 for odd numbers or when x equals to 2 for even numbers the step is being changed from positive to negative.

To print the numbers in ascending order :

const s = 10

for ( x=0,step=1; x!== -1 ; x===s ? (step = -1, x = x+step): x= x+step) {
    console.log(x)
}



来源:https://stackoverflow.com/questions/64692314/print-number-patterns-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!