打印到控制台时,在句子结尾处取消定义

时间:2017-11-13 03:37:01

标签: javascript recursion

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));

1 个答案:

答案 0 :(得分:0)

问题是在最后调用你的函数什么都没有返回所以它打印undefined你应该尝试返回一些像空字符串尝试这个代码而不确定这是否会做你想要的但是试一试

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));