在递归函数

时间:2017-01-23 14:40:33

标签: javascript recursion

我有一个函数,记录函数在一个素数数组中查找目标数所需的函数调用次数。我目前使用的是在全局范围内声明的计数器。如何将此计数器作为静态变量放入函数作用域中,以便每次调用函数时它都不会更改?

let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
let counter = 1

function findPrime(arr, target){

  let guess = arr[Math.floor(arr.length/2)]

  if (guess > target){

    arr = arr.splice(0, arr.length/2)
    counter ++
    findPrime(arr,target)

  }else if (guess < target){

    arr = arr.slice(arr.length/2)
    counter ++ || 1
    findPrime(arr,target)

  }else{

    console.log('guesses taken: ' + counter)
    console.log('target is: ' + guess)

  }
}


findPrime(primes, 2)

2 个答案:

答案 0 :(得分:2)

您使功能返回更新的计数器,因此您不必全局维护它;见***评论:

&#13;
&#13;
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

function findPrime(arr, target, counter) {             // ***
  if (typeof counter === "undefined") {                // ***
    counter = 1;                                       // ***
  }                                                    // ***

  let guess = arr[Math.floor(arr.length / 2)]

  if (guess > target) {

    arr = arr.splice(0, arr.length / 2)
    return findPrime(arr, target, counter + 1)         // ***

  } else if (guess < target) {

    arr = arr.slice(arr.length / 2)
    return findPrime(arr, target, counter + 1)         // ***

  } else {

    console.log('guesses taken: ' + counter)
    console.log('target is: ' + guess)
    return counter;
  }
}


findPrime(primes, 2)
&#13;
&#13;
&#13;

通常,递归函数接受并返回允许它们跟踪和控制递归的信息。虽然你可以通过关闭一个非全局变量来做到这一点,但这并不是他们通常做的事情(虽然有例外)。

答案 1 :(得分:0)

您可以将计数器包装在功能范围内。

let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

function findPrime(arr, target) {
    var counter = 1
    function findPrimeInner(arr, target){
        var guess = arr[Math.floor(arr.length/2)]

        if (guess > target) {
            arr = arr.splice(0, arr.length/2)
            counter ++
            findPrimeInner(arr,target)
        }else if (guess < target){

            arr = arr.slice(arr.length/2)
            counter ++ || 1
            findPrimeInner(arr,target)

        }else {
            console.log('guesses taken: ' + counter)
            console.log('target is: ' + guess)
        }
    }
    findPrimeInner(arr, target);
}

findPrime(primes, 5)