在JavaScript中重复字符串的三种方法
In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves repeating a string a certain number of times.
在本文中,我将解释如何解决freeCodeCamp的“ 重复字符串重复字符串 ”挑战。 这涉及重复一个字符串一定次数。
There are the three approaches I’ll cover:
我将介绍三种方法:
- using a while loop使用while循环
- using recursion使用递归
- using ES6 repeat() method使用ES6 repeat()方法
算法挑战说明 (The Algorithm Challenge Description)
Repeat a given string (first argument)
num
times (second argument). Return an empty string ifnum
is not a positive number.重复给定的字符串(第一个参数)
num
次(第二个参数)。 如果num
不是正数,则返回一个空字符串。
function repeatStringNumTimes(str, num) {return str;
}
repeatStringNumTimes("abc", 3);
提供的测试用例 (Provided test cases)
repeatStringNumTimes("*", 3) should return "***".repeatStringNumTimes("abc", 3) should return "abcabcabc".repeatStringNumTimes("abc", 4) should return "abcabcabcabc".repeatStringNumTimes("abc", 1) should return "abc".repeatStringNumTimes("*", 8) should return "********".repeatStringNumTimes("abc", -2) should return "".
方法1:使用While循环重复字符串 (Approach 1: Repeat a String with a While Loop)
A while statement executes its statement as long as a specified condition evaluates to true.
只要指定条件的值为真,while语句就会执行其语句。
A while statement looks like this:
一会儿语句看起来像这样:
while (condition)statement
with a condition which is evaluated before each pass through the loop. If the condition is true, the statement is executed. If the condition is false, the execution continues with any statement after the while loop.
条件,条件在每次通过循环之前进行评估。 如果条件为真,则执行该语句。 如果条件为假,则在while循环后继续执行任何语句。
The statement is executed as long as the condition is true. Here’s the solution:
只要条件为真,就执行该语句。 解决方法如下:
function repeatStringNumTimes(string, times) {// Step 1. Create an empty string that will host the repeated stringvar repeatedString = "";// Step 2. Set the While loop with (times > 0) as the condition to checkwhile (times > 0) { // As long as times is greater than 0, the statement is executed// The statementrepeatedString += string; // Same as repeatedString = repeatedString + string;times--; // Same as times = times - 1;}/* While loop logicCondition T/F repeatedString += string repeatedString timesFirst iteration (3 > 0) true "" + "abc" "abc" 2Second iteration (2 > 0) true "abc" + "abc" "abcabc" 1Third iteration (1 > 0) true "abcabc" + "abc" "abcabcabc" 0Fourth iteration (0 > 0) false}*/// Step 3. Return the repeated stringreturn repeatedString; // "abcabcabc"
}repeatStringNumTimes("abc", 3);
And again, without comments:
再说一次,不加评论:
function repeatStringNumTimes(string, times) {var repeatedString = "";while (times > 0) {repeatedString += string;times--;}return repeatedString;
}
repeatStringNumTimes("abc", 3);
方法2:使用条件和递归重复一个字符串 (Approach 2: Repeat a String using a Conditional and Recursion)
Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. There are a few key features of recursion that must be included in order for it to work properly.
递归是一种迭代操作的技术,方法是使函数重复调用自身直到获得结果。 为了使其正常工作,必须包含递归的一些关键功能。
The first is a base case: this is a statement, usually within a conditional clause like
if
, that stops the recursion.第一个是基本情况 :这是一条语句,通常在条件子句(如
if
,该语句停止递归。The second is a recursive case: this is the statement where the recursive function is called on itself.
第二种是递归的情况 :这是在其自身上调用递归函数的语句。
Here’s the solution:
解决方法如下:
function repeatStringNumTimes(string, times) {// Step 1. Check if times is negative and return an empty string if trueif (times < 0) {return "";}// Step 2. Check if times equals to 1 and return the string itself if it's the case.if (times === 1) {return string;}// Step 3. Use recursionelse {return string + repeatStringNumTimes(string, times - 1); // return "abcabcabc";}/* First Part of the recursion methodYou need to remember that you won’t have just one call, you’ll have several nested callstimes string + repeatStringNumTimes(string, times - 1)1st call 3 "abc" + ("abc", 3 - 1)2nd call 2 "abc" + ("abc", 2 - 1)3rd call 1 "abc" => if (times === 1) return string;4th call 0 "" => if (times <= 0) return "";Second part of the recursion method4th call will return ""3rd call will return "abc"2nd call will return "abc"1st call will return "abc"The final call is a concatenation of all the stringsreturn "abc" + "abc" + "abc"; // return "abcabcabc";*/
}
repeatStringNumTimes("abc", 3);
And again, without comments:
再说一次,不加评论:
function repeatStringNumTimes(string, times) {if(times < 0) return "";if(times === 1) return string;else return string + repeatStringNumTimes(string, times - 1);
}
repeatStringNumTimes("abc", 3);
方法3:使用ES6 repeat()方法重复一个字符串 (Approach 3: Repeat a String using ES6 repeat() method)
For this solution, you’ll use the String.prototype.repeat() method:
对于此解决方案,您将使用String.prototype.repeat()方法:
The
repeat()
method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.repeat()
方法构造并返回一个新字符串,该字符串包含指定数量的被调用的字符串的副本,并串联在一起。
Here’s the solution:
解决方法如下:
function repeatStringNumTimes(string, times) {//Step 1. If times is positive, return the repeated stringif (times > 0) { // (3 > 0) => truereturn string.repeat(times); // return "abc".repeat(3); => return "abcabcabc";}//Step 2. Else if times is negative, return an empty string if trueelse {return "";}
}repeatStringNumTimes("abc", 3);
And again, without comments:
再说一次,不加评论:
function repeatStringNumTimes(string, times) {if (times > 0)return string.repeat(times);elsereturn "";
}
repeatStringNumTimes("abc", 3);
You can use a ternary operator as a shortcut for the if/else statement, like this:
您可以将三元运算符用作if / else语句的快捷方式,如下所示:
times > 0 ? string.repeat(times) : "";
This can be read as:
可以理解为:
if (times > 0) { return string.repeat(times);
} else {return "";
}
You can then return the ternary operator in your function:
然后,您可以在函数中返回三元运算符:
I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the freeCodeCamp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.
希望对您有所帮助。 这是我关于freeCodeCamp算法挑战的“如何解决FCC算法”系列文章的一部分,在该系列文章中我提出了几种解决方案并逐步解释了实际情况。
Two ways to confirm the ending of a String in JavaScriptIn this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.
在JavaScript中确认字符串结尾的两种方法 在本文中,我将解释如何解决freeCodeCamp的“确认结尾”挑战。
Three Ways to Reverse a String in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”
在JavaScript中反转字符串的三种方法 本文基于Free Code Camp基本算法脚本“反转字符串”
Three Ways to Factorialize a Number in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”
在JavaScript中分解数字的三种方法 本文基于Free Code Camp基本算法脚本“简化数字”
Two Ways to Check for Palindromes in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.
用JavaScript检查回文的两种方法 本文基于Free Code Camp基本算法脚本“检查回文”。
Three Ways to Find the Longest Word in a String in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.
在JavaScript中查找字符串中最长单词的三种方法 本文基于Free Code Camp基本算法脚本“查找字符串中最长单词”。
Three Ways to Title Case a Sentence in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.
用JavaScript给句子加标题的三种方法 本文基于Free Code Camp基本算法脚本“标题加句子”。
If you have your own solution or any suggestions, share them below in the comments.
如果您有自己的解决方案或任何建议,请在下面的评论中分享。
Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)
或者,您也可以在单击下面的绿色心脏之后立即在Medium , Twitter , Github和LinkedIn上关注我;-)
#StayCurious, #KeepOnHacking & #MakeItHappen!
#StayCurious,#KeepOnHacking和#MakeItHappen!
其他资源 (Additional Resources)
while loop — MDN
while循环— MDN
repeat() method — MDN
repeat()方法— MDN
recursion — MDN
递归— MDN
Ternary Operator — MDN
三元运算符— MDN
翻译自: https://www.freecodecamp.org/news/three-ways-to-repeat-a-string-in-javascript-2a9053b93a2d/
相关文章:

杭电2099 整除的尾数
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid2099 解题思路:将a扩大100倍之后,再给它从加上i(i从0到99),一个一个的看哪一个能整除 反思:末两位是00的时候输出的是00(这种情况题目里面的测试数据给…

iOS 验证码倒计时按钮
具体使用 [SmsTimerManager sharedManager].second (int)time; [[SmsTimerManager sharedManager] resetTime]; [SmsTimerManager sharedManager].delegate self; [strongSelf updateTime];设置代理方法 更新按钮的标题 (void)updateTime { if ([SmsTimerManager sharedMan…

树莓派centos安装的基本配置
萌新再发一帖,这篇文章呢主要是为大家在树莓派上安装centos以后提供一个问题的解决方案。 首先我呢觉得好奇就在某宝上花了两百来块钱买了一套树莓派,很多人喜欢在树莓派上安装Debian,我呢更青睐用Red Hat的系统,毕竟对Red Hat更熟…

token拦截器阻止连接_如何防止广告拦截器阻止您的分析数据
token拦截器阻止连接TL;DR Theres dataunlocker.com service coming soon (subscribe!), along with the open-sourced prototype you can use for Google Analytics or Google Tag Manager (2020 update).TL; DR即将推出dataunlocker.com服务 (订阅!),以…

使用Fiddler手机抓包https-----重要
Fiddler不仅可以对手机进行抓包,还可以抓取别的电脑的请求包,今天就想讲一讲使用Fiddler手机抓包! 使用Fiddler手机抓包有两个条件: 一:手机连的网络或WiFi必须和电脑(使用fiddler)连的网络或Wi…

strtok和strtok_r
strtok和strtok_r原型:char *strtok(char *s, char *delim); 功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。 说明:首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。 …

iOS 标签自动布局
导入SKTagFrame SKTagFrame *frame [[SKTagFrame alloc] init];frame.tagsArray self.bigModel.Tags;// 添加标签CGFloat first_H 0;CGFloat total_H 0;for (NSInteger i 0; i< self.bigModel.Tags.count; i) {UIButton *tagsBtn [UIButton buttonWithType:UIButtonT…

引导分区 pbr 数据分析_如何在1小时内引导您的分析
引导分区 pbr 数据分析by Tim Abraham蒂姆亚伯拉罕(Tim Abraham) 如何在1小时内引导您的分析 (How to bootstrap your analytics in 1 hour) Even though most startups understand how critical data is to their success, they tend to shy away from analytics — especial…

SSL 1460——最小代价问题
Description 设有一个nm(小于100)的方格(如图所示),在方格中去掉某些点,方格中的数字代表距离(为小于100的数,如果为0表示去掉的点),试找出一条从A(左上角)到B(右下角&am…

在Windows 7下面IIS7的安装和 配置ASP的正确方法
在Windows 7下如何安装IIS7,以及IIS7在安装过程中的一些需要注意的设置,以及在IIS7下配置ASP的正确方法。 一、进入Windows 7的 控制面板,选择左侧的打开或关闭Windows功能 。二、打开后可以看到Windows功能的界面,注意选择的项目…

适配iOS 13 tabbar 标题字体不显示以及返回变蓝色的为问题
// 适配iOS 13 tabbar 标题字体不显示以及返回变蓝色的为问题 if (available(iOS 13.0, *)) {//[[UITabBar appearance] setUnselectedItemTintColor:Color_666666];}

企业不要求工程师资格认证_谁说工程师不能成为企业家?
企业不要求工程师资格认证by Preethi Kasireddy通过Preethi Kasireddy 谁说工程师不能成为企业家? (Who says engineers can’t become entrepreneurs?) A lot of people warned me not to walk away from my great position at Andreessen Horowitz to pursue so…

BestCoder Round #92 比赛记录
上午考完试后看到了晚上的BestCoder比赛,全机房都来参加 感觉压力好大啊QAQ,要被虐了. 7:00 比赛开始了,迅速点进了T1 大呼这好水啊!告诉了同桌怎么看中文题面 然后就开始码码码,4分16秒AC了第一题 7:05 开始看第二题 诶诶诶!!~~~~直接爆搜不久能过吗? 交了一发爆搜上去,AC了,…

[cocos2dx UI] CCLabelAtlas 为什么不显示最后一个字
CClabelAtlas优点,基本用法等我就不说了,这里说一个和美术配合时的一个坑!就是图片的最后一位怎么也不显示,如下图中的冒号不会显示 查了ASCII码表,这个冒号的值为58,就是在9(57)的后…

iOS 13 适配TextField 崩溃问题
iOS 13 之后直接通过以下方式修改Textfield的时候会出现报错信息 [_accountText setValue:Color_666666 forKeyPath:"_placeholderLabel.textColor"]; 报错信息 Access to UITextField’s _placeholderLabel ivar is prohibited. This is an application bug 解决…

测试django_如何像专业人士一样测试Django Signals
测试djangoby Haki Benita通过Haki Benita 如何像专业人士一样测试Django Signals (How to test Django Signals like a pro) For a better reading experience, check out this article on my website.为了获得更好的阅读体验,请在我的网站上查看此文章 。 Djang…

C#中静态方法的运用和字符串的常用方法(seventh day)
又来到了今天的总结时间,由于昨天在云和学院学的知识没有弄懂,今天老师又专门给我们非常详细地讲了一遍,在这里非常谢谢老师。O(∩_∩)O 话不多说,下面就开始为大家总结一下静态方法的运用和字符串的常用方法。 理论:静…

raid 磁盘阵列
mkdir /uuu #建挂载目录echo "- - -" > /sys/class/scsi_host/host2/scan #扫描新硬盘 lsblk #查看 parted /dev/sdb #分区 parted /dev/sdc lsblk mdadm -Cv /dev/md1 -l1 -n2 -c128 /dev/sd[b,c]1 #raid1配置, /dev/md1名字&#…

iOS 13 如何删除SceneDelegate
Xcode11之后新创建的工程会多出两个文件SceneDelegate。那么我们如何让它变回之前的那样的工程呢。 一、将这两个文件删除。 会报错There is no scene delegate set. A scene delegate class must be specified to use a main storyboard file. 二、将Info.plist 中的 SceneMai…

女性程序员大会ghc_在女性科技大会上成为男人的感觉
女性程序员大会ghcby Elijah Valenciano通过伊莱贾瓦伦西亚诺 在女性科技大会上成为男人的感觉 (What It’s Like to be a Man at a Women’s Tech Conference) To be honest, I was very nervous. A few panicked thoughts started to flood my mind as I prepared myself to…

cf776G.Sherlock and the Encrypted Data
题意:对于一个16进制数x,把x的各个数位拿出来,设其为t1,t2,...,定义s(x)为2^t1|2^t2|...,如x0x3e53,则s(x)2^3|2^14|2^5|2^316424.给出q组询问l,r(l,r也是16进制数,不超过15位),求[l,r]中有多少个数x满足x^s(x)<x. 这题题解写的是个状压数位dp,但是蒟蒻不会数位dp,自己YY了一…

c++, 派生类的构造函数和析构函数 , [ 以及operator=不能被继承 or Not的探讨]
说明:文章中关于operator实现的示例,从语法上是对的,但逻辑和习惯上都是错误的。 参见另一篇专门探究operator的文章:《c,operator》http://www.cnblogs.com/mylinux/p/4113266.html 1.构造函数与析构函数不会被继承&a…

json转换模型利器--JSONExport
JSONExport 从json 到 Model ,如此的方便 swift oc java 全部支持

亚马逊ses如何发qq_使用Amazon SES发送电子邮件
亚马逊ses如何发qqby Kangze Huang黄康泽 使用Amazon SES发送电子邮件 (Sending emails with Amazon SES) 完整的AWS Web样板-教程3 (The Complete AWS Web Boilerplate — Tutorial 3) 目录 (Table of Contents) Part 0: Introduction to the Complete AWS Web Boilerplate第…

源码-0205-02--聊天布局
还真是失败,搞了两天遇到了布局cell高度总是出差的问题,cell height不是高很多很多,就是就是矮到没有的情况。。。。糟糕透顶待解救~ 聊天布局 // // XMGChatingViewController.m // 07-聊天布局 #import "XMGChatingViewC…

js实现页面跳转的几种方式
第一种:<script language"javascript" type"text/javascript"> window.location.href"login.jsp?backurl"window.location.href; </script>第二种: <script language"javascript&q…

Mac 升级系统 pod 命令无效
mac 升级完最新的系统之后 使用pod 命令之后无效报错 -bash: /usr/local/bin/pod: /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby: bad interpreter: No such file or directory 解决方案 sudo gem install -n /usr/local/bin cocoapods

node seneca_使用Node.js和Seneca编写国际象棋微服务,第1部分
node seneca(This is Part 1 of a three-part series [Part 2, Part 3])(这是一个由三部分组成的系列文章的第1部分[ 第2 部分 , 第3部分 ]) I’ve begun wrapping my head around microservices. Up to this time I regarded it as a scalability pattern and ove…

Ubuntu中基于QT的系统网线连接状态的实时监视
1.必要准备 需包: #include <QNetworkInterface> 2.实现获取当前的网线连接状态 以下是自己在网络上搜到的一个解决方法,且没有加入iface.flags().testFlag(QNetworkInterface::IsRunning) 这一逻辑判断,经测试实时性极不可靠ÿ…

iOS 开发者账号 到期续费问题
https://blog.csdn.net/liruiqing520/article/details/104043221