在JavaScript中打印数字模式 [英] Print number patterns in JavaScript

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

问题描述

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

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.

如果我给出 s = 7 ,则输出模式将为 7、5、3、1、3、5、7

If I give s = 7 the output pattern would be 7, 5, 3, 1, 3, 5, 7

如果 s = 6 ,则输出为 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)
}

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

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

推荐答案

使用三元运算符:

const s = 10, b = 2

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

这篇关于在JavaScript中打印数字模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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