在JavaScript中反转字符串的三种方法

This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

本文基于Free Code Camp基本算法脚本“ Reverse a String ”

Reversing a string is one of the most frequently asked JavaScript question in the technical round of interview. Interviewers may ask you to write different ways to reverse a string, or they may ask you to reverse a string without using in-built methods, or they may even ask you to reverse a string using recursion.

反转字符串是技术面试中最常问到JavaScript问题之一。 采访者可能会要求您编写不同的方式来反转字符串,或者他们可能会要求您不使用内置方法来反转字符串,甚至会要求您使用递归来反转字符串。

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.

可能有数十种不同的方法可以执行此操作,但内置的反向功能除外,因为JavaScript没有。

Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.

以下是我解决JavaScript中的字符串反转问题的三种最有趣的方法。

算法挑战 (Algorithm Challenge)

Reverse the provided string.

反转提供的字符串。

Reverse the provided string.You may need to turn the string into an array before you can reverse it.

反转提供的字符串。 您可能需要将字符串转换为数组,然后才能将其反转。

Reverse the provided string.You may need to turn the string into an array before you can reverse it.Your result must be a string.

反转提供的字符串。 您可能需要将字符串转换为数组,然后才能将其反转。 您的结果必须是字符串。

function reverseString(str) {return str;
}
reverseString("hello");

提供的测试用例 (Provided test cases)

  • reverseString(“hello”) should become “olleh”

    reverseString(“ hello”)应该变成“ olleh”

  • reverseString(“Howdy”) should become “ydwoH”

    reverseString(“ Howdy”)应该变成“ ydwoH”

  • reverseString(“Greetings from Earth”) should return”htraE morf sgniteerG”

    reverseString(“来自地球的问候”)应该返回“ htraE morf sgniteerG”

1.使用内置函数反转字符串 (1. Reverse a String With Built-In Functions)

For this solution, we will use three methods: the String.prototype.split() method, the Array.prototype.reverse() method and the Array.prototype.join() method.

对于此解决方案,我们将使用三种方法:String.prototype.split()方法,Array.prototype.reverse()方法和Array.prototype.join()方法。

  • The split() method splits a String object into an array of string by separating the string into sub strings.

    split()方法通过将字符串对象拆分为子字符串,将String对象拆分为字符串数组。
  • The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.

    reverse()方法将数组反转到位。 第一个数组元素变为最后一个,最后一个数组变为第一个。
  • The join() method joins all elements of an array into a string.

    join()方法将数组的所有元素连接到字符串中。
function reverseString(str) {// Step 1. Use the split() method to return a new arrayvar splitString = str.split(""); // var splitString = "hello".split("");// ["h", "e", "l", "l", "o"]// Step 2. Use the reverse() method to reverse the new created arrayvar reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();// ["o", "l", "l", "e", "h"]// Step 3. Use the join() method to join all elements of the array into a stringvar joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");// "olleh"//Step 4. Return the reversed stringreturn joinArray; // "olleh"
}reverseString("hello");

将这三种方法链接在一起: (Chaining the three methods together:)

function reverseString(str) {return str.split("").reverse().join("");
}
reverseString("hello");

2.用递减的For循环反转字符串 (2. Reverse a String With a Decrementing For Loop)

function reverseString(str) {// Step 1. Create an empty string that will host the new created stringvar newString = "";// Step 2. Create the FOR loop/* The starting point of the loop will be (str.length - 1) which corresponds to the last character of the string, "o"As long as i is greater than or equals 0, the loop will go onWe decrement i after each iteration */for (var i = str.length - 1; i >= 0; i--) { newString += str[i]; // or newString = newString + str[i];}/* Here hello's length equals 5For each iteration: i = str.length - 1 and newString = newString + str[i]First iteration:    i = 5 - 1 = 4,         newString = "" + "o" = "o"Second iteration:   i = 4 - 1 = 3,         newString = "o" + "l" = "ol"Third iteration:    i = 3 - 1 = 2,         newString = "ol" + "l" = "oll"Fourth iteration:   i = 2 - 1 = 1,         newString = "oll" + "e" = "olle"Fifth iteration:    i = 1 - 1 = 0,         newString = "olle" + "h" = "olleh"End of the FOR Loop*/// Step 3. Return the reversed stringreturn newString; // "olleh"
}reverseString('hello');

没有评论: (Without comments:)

function reverseString(str) {var newString = "";for (var i = str.length - 1; i >= 0; i--) {newString += str[i];}return newString;
}
reverseString('hello');

3.使用递归反转字符串 (3. Reverse a String With Recursion)

For this solution, we will use two methods: the String.prototype.substr() method and the String.prototype.charAt() method.

对于此解决方案,我们将使用两种方法:String.prototype.substr()方法和String.prototype.charAt()方法。

  • The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

    substr()方法以指定的字符数返回从指定位置开始的字符串中的字符。
"hello".substr(1); // "ello"
  • The charAt() method returns the specified character from a string.

    charAt()方法从字符串中返回指定的字符。
"hello".charAt(0); // "h"

The depth of the recursion is equal to the length of the String. This solution is not the best one and will be really slow if the String is very long and the stack size is of major concern.

递归的深度等于String的长度。 如果String非常长且堆栈大小是主要问题,则此解决方案不是最佳解决方案,并且会非常慢。

function reverseString(str) {if (str === "") // This is the terminal case that will end the recursionreturn "";elsereturn reverseString(str.substr(1)) + str.charAt(0);
/* 
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested callsEach call: str === "?"        	                  reverseString(str.subst(1))     + str.charAt(0)
1st call – reverseString("Hello")   will return   reverseString("ello")           + "h"
2nd call – reverseString("ello")    will return   reverseString("llo")            + "e"
3rd call – reverseString("llo")     will return   reverseString("lo")             + "l"
4th call – reverseString("lo")      will return   reverseString("o")              + "l"
5th call – reverseString("o")       will return   reverseString("")               + "o"Second part of the recursion method
The method hits the if condition and the most highly nested call returns immediately5th call will return reverseString("") + "o" = "o"
4th call will return reverseString("o") + "l" = "o" + "l"
3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h" 
*/
}
reverseString("hello");

没有评论: (Without comments:)

function reverseString(str) {if (str === "")return "";elsereturn reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");

条件(三元)运算符: (Conditional (Ternary) Operator:)

function reverseString(str) {return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");

Reversing a String in JavaScript is a small and simple algorithm that can be asked on a technical phone screening or a technical interview. You could take the short route in solving this problem, or take the approach by solving it with recursion or even more complex solutions.

在JavaScript中反转字符串是一种小型且简单的算法,可以在电话技术筛选或技术面试中询问。 您可以采用短路径解决此问题,也可以采用递归或更复杂的解决方案来解决。

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

希望对您有所帮助。 这是我的“如何解决FCC算法”系列文章的一部分,有关自由代码训练营算法挑战,我在其中提出了几种解决方案并逐步解释了幕后情况。

Three ways to repeat a string in JavaScriptIn this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…

在JavaScript中重复字符串的三种方法 在本文中,我将解释如何解决freeCodeCamp的“重复字符串重复字符串”挑战。 这涉及…

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 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 , GithubLinkedIn上关注我;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

‪#StayCurious‬,‪#KeepOnHacking‬和‪#MakeItHappen‬!

翻译自: https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/396464.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

c实现三角形角度大于一个值_初中数学三角形知识点小结

▊ 三角形两边定理:三角形两边的和大于第三边。推论:三角形两边的差小于第三边。▊ 三角形中位线定理三角形的中位线平行于第三边,并且等于它的一半。▊ 三角形的重心三角形的重心到顶点的距离是它到对边中点距离的2倍。在三角形中&#x…

【Spring】使用Spring和AMQP发送接收消息(下)

为什么80%的码农都做不了架构师?>>> 上篇讲了RabbitMQ连接工厂的作用是用来创建RabbitMQ的连接,本篇就来讲讲RabbitMQ的发送消息。通过RabbitMQ发送消息最简单的方式就是将connectionFactory Bean注入到服务层类中,并使用它创建C…

微软u盘安装工具_使用微软Winget工具安装软件教程

对于系统管理员来说,一款好用的软件包管理工具可以大大提高安装、部署、管理软件的效率。可之前只有 MscOS 和 Linux 官方才有软件包管理工具,微软官方现在终于为Windows系统发布了一款名为Winget的软件包管理工具,MS酋长下面就来为大家演示一…

ZOJ2930 The Worst Schedule(最小割)

题目大概说有n个任务,每个任务可以提前或推迟,提前或推迟各有一定的费用,有的任务一旦推迟另一个任务也必须推迟,问怎么安排任务使花费最少,且最少花费的条件下提前的任务数最多能多少。 问题就是要把各个任务分成两个…

为什么要free释放内存_为什么在Free Code Camp上列出一份工作要花1,000美元?

为什么要free释放内存by Michael D. Johnson迈克尔约翰逊(Michael D.Johnson) 为什么在Free Code Camp上列出一份工作要花1,000美元? (Why does it cost $1,000 to list a job on Free Code Camp?) I’ve recently spoken with employers looking for JavaScript …

python访问注册表_读取注册表的Python代码

如果“Uninstall”中有超过1024个子键怎么办?Use _winreg.QueryInfoKey(key)Python2:import errno, os, _winregproc_arch os.environ[PROCESSOR_ARCHITECTURE].lower()proc_arch64 os.environ[PROCESSOR_ARCHITEW6432].lower()if proc_arch x86 and not proc_ar…

ios 动画 隐藏tabbar_UITabBarViewController 的底部 tabBar 隐藏

iOS pushViewController 时候隐藏 TabBar 的可以用interfaceUIViewController (UINavigationControllerItem)property(nonatomic,readonly,strong)UINavigationItem*navigationItem;// Created on-demand so that a view controller may customize its navigation appearance.p…

JS进阶之---函数,立即执行函数

一、函数 函数声明、函数表达式、匿名函数 函数声明:使用function关键字声明一个函数,再指定一个函数名,叫函数声明。function name () { … } 函数表达式:使用function关键字声明一个函数,但未给函数命名,…

主线程中有多个handler的情况

https://www.cnblogs.com/transmuse/archive/2011/05/16/2048073.html转载于:https://www.cnblogs.com/genggeng/p/9806415.html

RandomForestClassifier(随机森林检测每个特征的重要性及每个样例属于哪个类的概率)...

#In the next recipe, well look at how to tune the random forest classifier. #Lets start by importing datasets:from sklearn import datasets X, y datasets.make_classification(1000)# X(1000,20) #y(1000) 取值范围【0,1】from sklearn.ensemble import RandomFores…

单因素方差分析_基于R语言开展方差分析(一)——单因素方差分析

基本原理方差分析(Analysis of variance, ANOVA)是用于两个或两个以上样本均数比较的方法,还可以分析两个或多个研究因素的交互交互作用以及回归方程的线性假设检验等。其基本思想是将全部观察值间的变异——总变异按设计和需要分解成两个或多个组成部分&#xff0c…

个税10% 人群_人群管理如何使我们的搜索质量提高27%

个税10% 人群by Thanesh Sunthar由塔内什桑塔尔(Thanesh Sunthar) 人群管理如何使我们的搜索质量提高27% (How Crowd Curation Improved Our Search Quality by 27%) The bigger your platform gets, the more vital search becomes. And if you run a content-hea…

mysql增数据语句_Mysql 数据增删改查语句

插入数据 insert#1. 插入完整数据(顺序插入)#语法一:insert into 表名(字段1,字段2,字段3…字段n) values (值1,值2,值3…值n);#语法二:insert into 表名 values (值1,值2,值3…值n);#2. 指定字段插入数据#语法:insert into 表名(字段1,字段2…

Python+Flask.0010.FLASK即插视图之自定义视图类及修饰器

2019独角兽企业重金招聘Python工程师标准>>> 即插视图; 说明: FLASK的视图灵感来自于DJANGO的基于类而非基于函数的通用视图,主要目的是为了解决多个视图函数之间已经实现的部分,通过类继承的方式继承到其它视图,总之为了一点,就是少写代码,然后通过add_url_rule让我…

InputStream和Reader,FileInputStream和 FileReader的区别

一、InputStream和Reader的区别 InputStream和Reader都可以用来读数据(从文件中读取数据或从Socket中读取数据),最主要的区别如下: InputStream用来读取二进制数(字节流),而 Reader用来读取文本数据,即 Unicode字符。那么二进制数与文本数据有…

NGUI之输入文本框的使用

ToolBar中的两个红圈 另,代码如下:只需要定义一个变量即可,然后将控件drag到那里,真的是灰常方便呀 还有一个就是保存了(OK的响应),可以简单地理解为存档或读档 转载于:https://www.cnblogs.com/YTYMblog/p…

ae制作数据可视化_我如何精心制作真正可怕的数据可视化

ae制作数据可视化by Krist Wongsuphasawat克里斯特旺苏帕萨瓦(Krist Wongsuphasawat) 我如何精心制作真正可怕的数据可视化 (How I carefully crafted a truly terrible data visualization) Yes, you read that right. I am going to explain how I put together a really ba…

tensorrt轻松部署高性能dnn推理_实战教程:TensorRT中递归神经网络的介绍(中文字幕)...

NVIDIA TensorRT是一个高性能的深度学习推理优化器和运行时,它提供低延迟和高吞吐量。TensorRT可以从每个深度学习框架导入经过训练的模型,从而轻松地创建可以集成到大型应用程序和服务中的高效推理引擎。这个视频的五个关键点:1.TensorRT支持RNNv2, Mat…

w怎么接显示 树莓派zero_纯干货!一根线玩转树莓派ZeroW(图文教程,亲测有效)...

#一、写在前面本文旨在介绍如何用最少的外设(成本)完成树莓派Zero W最基础最重要的功能。注意:本文原始发表时官方镜像版本是2017-04-10的,在2019年5月10日有网友提出本方案已经不完全适用最新的镜像了,所以如果只是想按照本文所提出的步骤一…

十进制小数转换二进制的问题

2019独角兽企业重金招聘Python工程师标准>>> 整数和小数分别转换。 整数除以2,商继续除以2,得到0为止,将余数逆序排列。 22 / 2 11 余0 11/2 5 余 1 5 /2 2 余 1 2 /2 1 余 0 1 /2 0 余 1 所以22的二进制…