javascript函数返回意外的未定义

时间:2013-10-08 08:00:03

标签: javascript function

我一定错过了一些愚蠢的东西,但为什么sumArray会回归undefined ???

<script>

    function sumArray(arr, n, sum){
        if(n == 0){
            console.log( arr[0] + sum ); // log shows 15 as expected
            return  arr[0] + sum;        // the function would return undefined
        }else{
            sum = sum + arr[n-1];
            sumArray(arr, n-1, sum); 
        }
    }

    var arr1 = [0,1,2,3,4,5];
    var result = sumArray(arr1, arr1.length, 0)

    console.log(result); // returns Undefined !!!

</script>

1 个答案:

答案 0 :(得分:6)

变化:

else{
    sum = sum + arr[n-1];
    sumArray(arr, n-1, sum); 
}

else{
  sum = sum + arr[n-1];
  return sumArray(arr, n-1, sum); //return the function
}