在JavaScript中打印数字模式

编程入门 行业动态 更新时间:2024-10-28 11:22:13
本文介绍了在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中打印数字模式

本文发布于:2023-08-07 07:01:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   数字   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!