Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

javascript - Recursively add to strings in JS

I'm tackling a recursion problem that returns a string of "hi"'s where the first "hi" has a capital H and the string ends with an exclamation point. I have the code below so far but I'm not sure how to prevent subsequent occurrences of "hi" having a capital H. Any guidance would be welcome.

function greeting(n) {
  if (n === 0) {
    return "";
  } else if (n === 1) {
    return "Hi!"
  } else {
    return `${'Hi' + greeting(n - 1)}`
  }
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to work around your problem is to pass a flag to the function which indicates whether this is the first call, and only in that case capitalise the hi. Note that you can simplify the code slightly by returning a ! when n == 0; then you don't need to special case n == 1:

function greeting (n, first = true) {
  if (n === 0) {
    return "!";
  } 
  else {
    return `${(first ? 'Hi' : 'hi') + greeting(n - 1, false)}`
  } 
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...