在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.pswp.cn/news/396464.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396464.shtml
英文地址,請注明出處:http://en.pswp.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的二進制…