Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript函数只返回未定义的_Javascript - Fatal编程技术网

javascript函数只返回未定义的

javascript函数只返回未定义的,javascript,Javascript,下面的javascript函数只返回未定义的 function digital_root(n) { var x = String(n).split(''); if (x.length > 1) { sum = x.reduce((accumulator, value) => parseInt(value) + accumulator, 0); digital_root(sum); } else { console.log(x); retur

下面的javascript函数只返回未定义的

function digital_root(n) {
  var x = String(n).split('');
  if (x.length > 1) {
    sum = x.reduce((accumulator, value) => parseInt(value) + accumulator, 0);
    digital_root(sum);
  } else {
    console.log(x);
    return x;
  }
}
> digital_root(12)
undefined
但是,在节点中运行时,它会打印正确的值。那么为什么它返回未定义的值呢

> digital_root(12)
[ '3' ]
undefined

如果我取出
console.log(x)
语句,函数仍然返回未定义的

function digital_root(n) {
  var x = String(n).split('');
  if (x.length > 1) {
    sum = x.reduce((accumulator, value) => parseInt(value) + accumulator, 0);
    digital_root(sum);
  } else {
    console.log(x);
    return x;
  }
}
> digital_root(12)
undefined

第一次运行函数时,它进入
if
块,在那里它用参数
digital\u root(3)
再次调用自己

现在首先处理这个“内部”调用,这次进入
else
块,在那里发生
console.log(x)
调用,然后
return['3']
显式地将该值返回给外部函数调用,因此返回值不会显示在控制台上

内部调用返回值后,外部函数终止,因为没有什么事情可做,所以外部函数永远不会返回任何东西


如果没有明确的
返回
语句,函数确实有一个默认返回值
未定义

。我需要为递归调用包含
return

完整的代码应该如下所示

function digital_root(n) {
  var x = String(n).split('');
  if (x.length > 1) {
    sum = x.reduce((accumulator, value) => parseInt(value) + accumulator, 0);
    return digital_root(sum);
  } else {
    console.log(x);
    return x;
  }
}

如果我取出
console.log(x)
语句,函数仍然只返回undefined。但是,我知道应该返回
x
,因为它可以打印。还是我误解了一些基本的东西?if true分支中的返回声明在哪里?@MarianTheisen你是对的,这就是问题所在。我没有意识到我也需要一个返回声明。