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/

在JavaScript中反转字符串的三种方法相关推荐

  1. 在JavaScript中重复字符串的三种方法

    In this article, I'll explain how to solve freeCodeCamp's "Repeat a string repeat a string" ...

  2. 中单引号怎么转义_在JavaScript中组合字符串的4种方法

    下面是在JavaScript中组合字符串的4种方法.我最喜欢的方法是使用模板字符串.为什么?因为它更具可读性,所以没有转义引号的反斜杠,没有笨拙的空格分隔符,也没有混乱的加号操作符 . const i ...

  3. 在JavaScript中组合字符串的4种方法

    下面是在JavaScript中组合字符串的4种方法.我最喜欢的方法是使用模板字符串.为什么?因为它更具可读性,所以没有转义引号的反斜杠,没有笨拙的空格分隔符,也没有混乱的加号操作符

  4. 在 JavaScript 中比较字符串的 4 种方法

    严格平等 要确定字符串是否相等,可以使用严格相等运算符 .如果字符串不同,则返回,如果字符串相同,则返回===falsetrue const s1 = 'learn'; const s2 = 'tod ...

  5. Java中遍历字符串的三种方法

    (1).length(), charAt() (2).length(), substring(i ,i+1) (3).toCharArray() String str="2019 come ...

  6. 如何在JavaScript中反转字符串?

    在不使用内置函数( .reverse() .charAt()等)的情况下,如何在将字符串传递给带有return语句的函数时在JavaScript中将字符串原地(或原地)反向? #1楼 以下技术(或类似 ...

  7. java浮点数化为整数_[Java教程]javascript浮点数转换成整数三种方法

    [Java教程]javascript浮点数转换成整数三种方法 0 2014-06-24 04:00:27 将浮点数转换成整数方法有很多,分享三种常用方法. Summary 暂时我就想到3个方法而已.如 ...

  8. mysql添加临时索引_mysql 中添加索引的三种方法

    在mysql中有多种索引,有普通索引,全文索引,唯一索引,多列索引,小伙伴们可以通过不同的应用场景来进行索引的新建,在此列出三种新建索引的方法 mysql 中添加索引的三种方法 1.1 新建表中添加索 ...

  9. centos 卸载软件_一篇看懂!详解-Linux系统中安装软件的三种方法

    Linux系统中安装软件的三种方法 注:本文主要以CentOS为例介绍常用的安装方式,其他版本linux在文章底部 Linux系统中怎么安装软件,首先说一下应用程序与系统命令的区别: 1.文件位置 系 ...

最新文章

  1. 网络设备转发数据包的整个流程_网络工程师(33):路由转发工作原理
  2. Jsp-request与requestScope的区别
  3. 元素、属性、标题、段落、文本格式化
  4. Floyd —Warshall(最短路及其他用法详解)
  5. Qt工作笔记-ListWidget拖动(拖拽)到QGraphicsScene
  6. ETDM:基于显式时间差分建模的视频超分辨率(CVPR 2022)
  7. 互联网思维心得体会1500字_读懂《天道》丁元英的3个“高人”思维,你少走10年职场弯路...
  8. CodeForces 840C - On the Bench | Codeforces Round #429 (Div. 1)
  9. Attaching the Script debugger to process ‘[****]’ on machine **** failed.
  10. WSUS服务器更改存放路径方法
  11. Bat+PowerShell实现windows网络一键共享
  12. 【校招VIP 前端】电影详情模块的开发文档设计实战
  13. springboot基于安卓的移动数字图书馆的设计与实现毕业设计源码030911
  14. php对接京东宙斯平台,利用京东联盟API获取自定义推广链接
  15. php泛目录站群系统,php泛目录站群
  16. 百度服务器自动重启,百度云服务器重启的两种方法介绍
  17. 7-1 宿舍谁最高?
  18. bem什么意思_BEM是什么意思
  19. 警惕:区块链十大安全事件
  20. 转载一个大神的Makefile

热门文章

  1. 小程序自定义组件中observer函数的应用
  2. 有效的形成传感器(执行器)的控制方式
  3. MVC架构 -- 初学试水选课管理系统
  4. 前端页面内含外显相关知识
  5. ftp如何预览图片 解决方案
  6. html中视频播放完后可以跳到另一个html
  7. 为什么下了android 4.1 的SDK后在本地用浏览器看api说明文档时,浏览器打开api的html文件很慢?试了好几款浏览器都一样。为什么?...
  8. docker 网络 不好用 docker: Error response from daemon: failed to create endpoint jovial_wing on network b
  9. 如何查看linux中文件打开情况
  10. 【无删减】Python老司机收藏夹的17个国外免费学习网站