这个变量是一个数组。为什么它返回未定义?

This variable is an array. Why is it returning undefined?

这是解决 Eloquent Javascript challenge in Chapter 4, A 列表的部分尝试。 theArray returns 未定义,但如果我只打印它的值,它就是我所期望的(值数组)。为什么它 return 未定义?

var obj = {"value":"C","rest":{"value":"B","rest":{"value":"A"}}};

var theArray =[];

var listToArray = function(list) {
  theArray.push(list.value);
    if(list.rest !== undefined) {
      listToArray(list.rest);
    } else return theArray; //console.log(theArray); returns the expected value
}

console.log(listToArray(obj));

你必须return递归调用,

 if(list.rest !== undefined) {
      return listToArray(list.rest);

DEMO

如果您不 return 递归调用,那么来自最终函数堆栈的 array 将不会被 return 编辑,而是 undefined returned.