当前位置:网站首页>通过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)
实现结果如上图,成功实现~很简单的其实。我没有看别人写的代码,虽然不是最优解,但这能够帮助一个前端更加熟练使用字符串,数组的方法,以及两者转换灵活应用,加强记忆。
边栏推荐
- ffmpeg 音频相关命令
- Proxy in ES6
- Ubuntu14 install MySQL and configure root account local and remote access
- CMU AI PhD 第一年总结
- Actual combat of flutter - fast implementation of audio and video call application
- DTD modeling
- GB28181之SIP协议
- 音频编解码基础知识
- Thesis reading [distinctive late semantic graph for video capturing]
- pickle.load报错【AttributeError: Can‘t get attribute ‘Vocabulary‘ on <module ‘__main__‘】
猜你喜欢

What must be done in graduation season before going to Shanhai

XML syntax, constraints

Regular expression =regex=regular expression

GB28181之SIP协议

DDR4 test-2
![[to.Net] C set class source code analysis](/img/59/4c7b910bc6505e5f81015ce80812fc.png)
[to.Net] C set class source code analysis

任务:拒绝服务DoS

SIP protocol of gb28181

Uni app wechat applet one click login to obtain permission function

Solidity - truncated and checked modes of arithmetic operations - new features of 0.8.0
随机推荐
Shell advanced
Contos 7 搭建sftp之创建用户、用户组以及删除用户
SIP protocol of gb28181
P2433 【深基1-2】小学数学 N 合一
Opencv video quality diagnosis - VIDEO occlusion diagnosis
Proxy in ES6
[SQL optimization] the difference between with as and temporary tables
118. 杨辉三角
118. Yanghui triangle
[Mori city] random talk on GIS data (I)
Contos 7 set up SFTP to create users, user groups, and delete users
Uni app product classification
ffmpeg 错误码
Uni app wechat applet one click login to obtain permission function
Dom4j parsing XML, XPath retrieving XML
音频编解码基础知识
Ffmpeg avframe to cv:: mat
[untitled]
GetMessage底层机制分析
Interview questions for audio and video positions in Dachang -- today's headline