Welcome to OStack Knowledge Sharing 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 Answer

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...