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 print语句,因此如何解决此问题?
这两个smallestInteger函数有不同的构造函数(第一个有1个参数,另一个有3个)就像重写一样,所以我不认为它们是在互相替换你看到它得到2个参数,它得到3个参数。最后,smallestInteger函数调用了smallestInteger辅助函数,它在?k == 0之后有退出条件,所以它不应该永远继续下去。仍然有同样的错误

最佳答案

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));
}

08-18 13:43