繁体   English   中英

使用递归 javascript 反转字符串

[英]reverse string using recursion javascript

在这个程序中,我尝试检查给定的输入是否为字符串,如果不是字符串意味着控制台输出输入值,否则使用递归 function 反转字符串。当我在代码中提供typeof时,出现错误在第一行,没有它它可以正常运行......

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

为什么不直接用这个?

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

您将字符串拆分为字符数组,将其反转并加入它。

您可以迭代字符串并使用charAt(str.length - 1)从字符串中获取元素。 然后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