[英]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.