为什么我的函数返回“newLine.unshift(startN) is not a function”

时间:2021-03-19 17:15:04

标签: javascript function recursion

我一直在尝试编写一个递归函数来获取一系列数字,但我收到一个错误消息,提示 'newLine. unshift(startN) is not a function'

以下是代码:

function rangeOfNumbers(startN, endN) {
  if (startN - endN === 0) {
    return "The starting number will always be less than or equal to the ending number";
  } else {
    const newLine = rangeOfNumbers(startN + 1, endN);
    newLine.unshift(startN);
    return newLine;
  }
}

console.log(rangeOfNumbers(1, 7));

有人可以帮我找到提到错误的原因吗?

1 个答案:

答案 0 :(得分:0)

rangeOfNumbers(1, 7) / newLine = rangeOfNumbers(2, 7)
rangeOfNumbers(2, 7) / newLine = rangeOfNumbers(3, 7)
...
rangeOfNumbers(7, 7) / newLine = "起始编号总是..."

typeof newLine = String
newLine.unshift() >> undefined // unshift 不可用 JS 字符串