当前位置:网站首页>通过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)
实现结果如上图,成功实现~很简单的其实。我没有看别人写的代码,虽然不是最优解,但这能够帮助一个前端更加熟练使用字符串,数组的方法,以及两者转换灵活应用,加强记忆。
边栏推荐
- Simplified pinduoduo product data
- 精耕渠道共謀發展 福昕攜手偉仕佳傑開展新產品培訓大會
- Crunch简介、安装,使用Crunch制作密码字典
- 【森城市】GIS数据漫谈(一)
- 科技T3国产平台!成功搭载“翼辉国产实时系统SylixOS”
- 简版拼多多商品数据
- Interview questions for audio and video positions in Dachang -- today's headline
- Wechat applet navigator has a shadow after clicking. Remove the shadow effect of navigator
- Collect Tiktok video
- Task: denial of service DOS
猜你喜欢
Axure does not display catalogs
Parallelism, concurrency and life cycle of threads
How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?
Wireshark packet analysis TCP, FTP
DTD modeling
Reading the paper [learning to discretely compose reasoning module networks for video captioning]
Optimization of video streaming with repeated requests in the case of unstable easygbs network
Facebook聊单,SaleSmartly有妙招!
[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function
Regular expression =regex=regular expression
随机推荐
ffmpeg 音频相关命令
IPv4 address, subnet mask, gateway
【org.slf4j.Logger中info()方法】
[to.Net] C set class source code analysis
Brpc understanding
Introduction and installation of crunch, and making password dictionary with crunch
DTD modeling
微信公众号开发相关流程及功能介绍
数字化转型企业成功的关键,用数据创造价值
[SQL optimization] the difference between with as and temporary tables
Learning records of building thingsboard, an Internet of things platform
118. Yanghui triangle
Compile ffmpeg source code with msys+vs2019 under win10
Learning notes [Gumbel softmax]
Summary of SQL query de duplication statistics methods
奔赴山海之前,毕业季一定要做的那些事情
新版国标GB28181视频平台EasyGBS如何配置WebRTC视频流格式播放?
音频编解码基础知识
wireshark报文分析tcp,ftp
博途V16 获取系统时间转换成字符串