繁体   English   中英

打印到控制台时,句子末尾变得不确定

[英]Getting undefined at the end of the sentence when printing to console

const words = ['hello', 'thank you', 'brother', 'welcome', 'dancing', 'milk', 'bike', 'ruffles'];

const getSentence = (words, index = 0) => {

  if (words[index] === undefined) {
    return;
  }
  return words[index] + ' ' + getSentence(words, index + 1)
}

console.log(getSentence(words));

问题是在上次调用中,您的函数未返回任何内容,因此它未定义打印,您应该尝试返回一些类似空字符串的内容,请尝试使用此代码,但不确定是否会执行您想要的操作,请尝试一下

const words = ['hello', 'thank you', 'brother', 'welcome', 'dancing', 'milk', 'bike', 'ruffles'];

const getSentence = (words, index = 0) => {

if (words[index] === undefined) {
    return '';
}
return words[index] + ' ' + getSentence(words, index + 1)
}

console.log(getSentence(words));

暂无
暂无

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

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