简体   繁体   English

递归函数返回预期的字符串值,有时是未定义的?

[英]Recursive functions returns expected string value and sometimes undefined?

The function randomly works as expected, and sometimes returns undefined . 该函数按预期随机运行,有时返回undefined That is what I do not understand. 那是我不明白的。

Can someone explain how javascript performs when it repeats function calls, for this example, in a recursive pattern. 有人可以解释一下javascript以递归方式重复执行函数调用时的性能。

The main function takes two arguments main功能有两个参数

First Arg: an integer which represents the number of characters it will take from the second argument. 第一个Arg:一个整数,表示它将从第二个参数获取的字符数。 Second Arg: A string. 第二个Arg:一个字符串。

The entire code 整个代码

var getRandomIntInteger = function (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function recursive(arr, string, limit) {

    if (string.length >= limit) {
        return string
    }
    else {
        // get random integer within the range of the array ength
        var randIndex = getRandomIntInteger(0, arr.length)
        // concatenate that value sitting at that index
        string += arr[randIndex]
        // remove that value from the array
        arr.splice(randIndex, 1)
        // re-run
        return recursive(arr, string, limit)
    }

}

var main = function(k, i) {
    let inputArray = Array.from(i)
    console.log('k=',k, 'inputArray length = ', inputArray.length)


    if (k >= i.length) {
        return 'sameple size must not exceed '
    }
    let s = ""
    var res = recursive(inputArray, s, k)
    console.log('result = ', res)
    return res

}

// run the function
main(4, "ABCDEFGHI")

This function call sometimes returns 4 random charactors and sometimes returns undefined even if the function is called with the same arguments. 即使使用相同的参数调用该函数,该函数调用有时也会返回4个随机字符,有时还会返回undefined。

By the manner you have defined your random function you should change this call: 通过定义随机函数的方式,您应该更改此调用:

 var randIndex = getRandomIntInteger(0, arr.length)

to this: 对此:

var randIndex = getRandomIntInteger(0, arr.length - 1)

... since the second argument is a number that could be produced by getRandomIntInteger , yet arr[arr.length] is always undefined . ...由于第二个参数是getRandomIntInteger可能产生的数字,但是arr[arr.length]始终undefined

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

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