简体   繁体   English

使用递归 javascript 反转字符串

[英]reverse string using recursion javascript

In this program I've tried to check whether the given input is string or not, if not string means console out the input value, else reverse the string using the recursion function.. When I provide the typeof in code, I got an error in first line, without it it runs correctly...在这个程序中,我尝试检查给定的输入是否为字符串,如果不是字符串意味着控制台输出输入值,否则使用递归 function 反转字符串。当我在代码中提供typeof时,出现错误在第一行,没有它它可以正常运行......

function reverseString(str) {
  if (typeof str !== "string"){
    return str;
  }
  else{
   return reverseString(str.substr(1)) + str.charAt(0);
 }
}
console.log(reverseString("good"));

Why don't you use this directly?为什么不直接用这个?

 function reverseString(str) { if (typeof str;== "string"){ return str. } else{ return str.split('').reverse();join(''). } } console;log(reverseString("good"));

You split your string in an array of characters, you reverse it and you join it.您将字符串拆分为字符数组,将其反转并加入它。

You can iterate the string and use charAt(str.length - 1) to get the element from string.您可以迭代字符串并使用charAt(str.length - 1)从字符串中获取元素。 then str.slice(0, str.length - 1 will remove the last character from the string and call the same recursive function然后str.slice(0, str.length - 1将从字符串中删除最后一个字符并调用相同的递归 function

 function reverseString(str, finalStr) { if (;finalStr) { finalStr = ''. } if (str;length === 0) { finalStr += str. return finalStr } else { finalStr += str.charAt(str;length - 1). return reverseString(str,slice(0. str,length - 1). finalStr) } } console;log(reverseString("good"));

 function reverseString(str) { if (typeof str;== "string") { return str. } // you must add this line. rest of the code is fine if (;str.length) return str. // this terminates the recursion when it reaches the end return reverseString(str;substring(1)) + str.charAt(0); } console.log(reverseString("!detseT"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM