当前位置:网站首页>通过js实现金字塔(星号金字塔,回文对称数字金字塔)
通过js实现金字塔(星号金字塔,回文对称数字金字塔)
2022-07-01 18:45:00 【伊格鲁】
先看一下实现效果是这样的:
每次看到像这种需要实现图形的,第一步其实要找的就是图形的规律。
从规律开始!
看到决定这副图形需要空格和’'。
从上往下,星星的数量是:1,3,5,7,9,11…
空格是数量是:9 8 7 6 5 4 3 2 1 0
那么星星的规律就是2n-1 , 空格就是每层递减1
但要通过js去实现,就需要从数组(即金字塔)的索引和长度的角度去写他们的规律,
那么星星就是: 2(索引值+1)-1 ,
而空格则是 :高度-索引值。
知道规律后,加一个字符串的方法:str.repeat(n)我们就可以实现数字金字塔啦~
代码如下:
function tar(n){
for(let i=0;i<n;i++){
let str1=' '
let str2 = str1.repeat(n-i)
let str3='*'
let str4 = str3.repeat(2*(i+1)-1)
console.log(str2+str4)
}
}
调用:
tar(10)
实现结果:
其实代码很简单,不懂别人为啥不用str.repeat,好省事hhhhh
进阶:做一个回文数字的金字塔。左右对称
先看一下实现结果:
呵呵,其实换汤不换药 还是继续找规律
n=0 是 1 n=1 是121 n=2 是12321
既然是回文,写一边就好了,另外一边通过数组方法(reverse)就可以了,转换成字符串拼接一起。
所以简化看是
n=0是1 n=1是12 n=2是123
实现代码:
// 实现回文数字
function countNum(n){
let arr=[]
for(let i=0;i<n;i++){
arr.push(i+1)
}
let str = arr.join("")
let arr1 = str.split("").reverse()
arr1.shift()
let str1 = arr1.join("")
return str+str1
}
//主代码
function tar(n){
for(let i=0;i<n;i++){
let str1=' '
let str2 = str1.repeat(n-i)
let str3 = countNum(i+1)
console.log(str2+str3)
}
}
调用:
tar(9)
实现结果如上图,成功实现~很简单的其实。我没有看别人写的代码,虽然不是最优解,但这能够帮助一个前端更加熟练使用字符串,数组的方法,以及两者转换灵活应用,加强记忆。
边栏推荐
- How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?
- Shell advanced
- 事务隔离级别 gap锁 死锁
- Dom4j parsing XML, XPath retrieving XML
- torch.nn.functional.interpolate函数
- Simplified pinduoduo product data
- uni-app商品分类
- [go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function
- Optimization of video streaming with repeated requests in the case of unstable easygbs network
- [to.Net] C set class source code analysis
猜你喜欢
随机推荐
Shell高级进阶
利用win7漏洞进行系统登录密码破解
Introduction and installation of crunch, and making password dictionary with crunch
Les canaux de culture intensive s'efforcent de développer Fu Xin et Wei Shi jiajie pour organiser une conférence de formation sur les nouveaux produits
[info() method in org.slf4j.logger]
EasyGBS主子码流都为H.265时,切换出现花屏如何解决?
类加载机制
宝,运维100+服务器很头疼怎么办?用行云管家!
Analysis of GetMessage underlying mechanism
白盒加密技术浅理解
Regular expression =regex=regular expression
OpenCV视频质量检测--清晰度检测
Parallelism, concurrency and life cycle of threads
uni-app微信小程序一键登录获取权限功能
How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?
Ffmpeg common commands (2)
How to correctly use vertx to operate redis (3.9.4 with source code analysis)
IPv4地址、子网掩码、网关
wireshark报文分析tcp,ftp
brpc理解