简体   繁体   English

用Java的递归函数填充数组?

[英]Recursive function in Javascript to fill Array?

I am trying to fill an array with ranges of values in a recursive function, but i see a weird thing happening while returning the array, though the array has values, when i alert it outside the function it gives me undefined. 我试图在递归函数中用值的范围填充数组,但是我看到返回数组时发生奇怪的事情,尽管该数组有值,当我在函数外警告它给我未定义时。 Not Sure whether its my code issue or any kind of behavior. 不确定是我的代码问题还是任何行为。

Same implementation when i tired using simple for loop it worked fine. 当我厌倦了使用简单的for循环时,它的实现也很好。

I don't know what title to give for this problem, please suggest me a good one. 我不知道该问题的标题,请给我推荐一个好标题。

JS Fiddle JS小提琴

With Recursion 递归

var arr = [];
function fillArray(n,i){
    if(arr.length !== n){
        if(i===0)
            arr[i] = i;
        else
            arr[i] = arr[i-1] + 1;
        fillArray(n,++i);
    }
    else{
         console.log(arr);
         return arr;
    }
}
console.log(fillArray(10,0));

With For Loop 与For循环

var arr = [];

function fillArray(start,end){
    for(var i=start,j=0;i<=end;i++,j++){
        arr[j] = i;
    }
    return arr;
}

alert(fillArray(1,10));

 function fillArray(n, i, a) { a.push(i); return a.length < n ? fillArray(n, ++i, a) : a; } console.log(fillArray(10, 0, [])); 

First, this is not a good example of something that should be implemented recursively in JavaScript. 首先,这不是应该在JavaScript中递归实现的示例。 It's unidiomatic. 这很简单。

The reason the result is undefined outside the function is that your code fails to return the result of each successive recursive call. 函数外部的结果undefined的原因是您的代码无法返回每个后续递归调用的结果。 The recursion statement should look like: 递归语句应类似于:

    return fillArray(n,++i);

Without that, the final call that does return the array will have its return value simply ignored by the penultimate call. 不这样做, 确实返回数组最后调用将其返回值简单地由倒数第二呼叫忽略。

Take a look on your example: 看一下您的示例:

var arr = [];
function fillArray(n,i){
    if(arr.length !== n){
        if(i===0)
            arr[i] = i;
        else
            arr[i] = arr[i-1] + 1;
        fillArray(n,++i); // ends without returning anything
    }
    else{
         console.log(arr);
         return arr; // return array
    }
}
console.log(fillArray(10,0));

First of all I wouldn't declare value outside function and I wouldn't do with recursion (as you pollute your closure. But if you do so and you keep your function as it is, don't expect value as return here (as you edit variable outside of it). 首先,我不会在函数外部声明值,也不会对递归进行声明(因为您污染了闭包。但是,如果这样做并保留了函数原样,则不要期望值返回此处(因为您可以在其外部编辑变量)。

var arr = [];
function fillArray(n,i){
    if(arr.length !== n){
        if(i===0)
            arr[i] = i;
        else
            arr[i] = arr[i-1] + 1;
        fillArray(n,++i);
    } // return not needed
}
fillArray(10,0);
console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM