最大调用堆栈超出RangeError

时间:2019-03-15 00:43:48

标签: javascript algorithm recursion stack

smallestInteger = (stack,numbers,k) => {
    if (stack.length == 0){
        stack.push(numbers[k]);
    }
    if (numbers[k] <= stack[stack.length-1]){
        stack.pop();
        stack.push(numbers[k]);
    } 
    console.log(`stack is ${stack}`)
    console.log("k:" + k);
    return (k == 0) ? stack[stack.length-1] : smallestInteger(stack,numbers,k-1);
}

var smallestInteger = function(numbers) {
    let stack = []; 
    let smallest = smallestInteger(stack ,numbers,numbers.length - 1);
    return `the smallest integer is ${smallest}`;
}

var testCases = [[10,2,5,7,15,9], [1,2,3,4]];
for (let testCase of testCases){
    console.log(smallestInteger(testCase));
}

运行> node smallestInteger.js会出现此错误:

RangeError: Maximum call stack size exceeded
    at smallestInteger (smallestInteger.js:17:31)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)
    at smallestInteger (smallestInteger.js:19:17)

因为代码未到达console.log打印语句,所以如何解决呢?

这两个smallestInteger函数具有不同的构造函数(第一个具有1个参数,另一个具有3个),就像重写一样,因此我不认为它们正在互相替换。您在哪里看到它得到2个参数,它得到了3个预期的参数。最后,smallestInteger函数正在调用smallestInteger辅助函数,该辅助函数在?k == 0之后确实具有退出条件,因此不应永远持续下去。仍然出现相同的错误

1 个答案:

答案 0 :(得分:1)

JavaScript不允许重载函数。为此,您需要发挥创造力。例如:

function smallestInteger(stack,numbers,k){
if (arguments.length == 1) {
    numbers = stack;
    stack = []; 
    let smallest = smallestInteger(stack ,numbers,numbers.length - 1);
    return `the smallest integer is ${smallest}`;
  }

if (stack.length == 0){
    stack.push(numbers[k]);
}
if (numbers[k] <= stack[stack.length-1]){
    stack.pop();
    stack.push(numbers[k]);
} 
return (k == 0) ? stack[stack.length-1] : smallestInteger(stack,numbers,k-1);
}

var testCases = [[10,2,5,7,15,9], [1,2,3,4]];
for (let testCase of testCases){
    console.log('testCase : ', testCase);
    console.log(smallestInteger(testCase));
}