总是调用比上次呼叫高+1的功能?

时间:2017-04-13 18:37:31

标签: javascript algorithm

每次调用input_function()时,参数需要比上次调用时高一个整数。它无法修改。

在下面的示例中,第一次迭代有效,但在第二次迭代时,将使用4的参数进行调用,该参数应为5

input_function(1)
input_function(2)

for i in 1..4
  input_function(2+i)
  # do something here with i
  input_function(3+i)
  # do something here with i
end

问题

如何确保input_function()的参数始终高于上次调用的参数?

解决方案可以是任何语言。

3 个答案:

答案 0 :(得分:0)

好吧,通常我会使用static variables来解决这类问题。不幸的是,Javascript不支持它。如果你想在Javascript中做类似的事情,你可以重新使用这个替代方案:

function input_function(n) {
    alert(n + count.num);
    count.num++;
}

// initialize count number
count.num = 0;

input_function(10); // alert 10
input_function(4); // alert 5
input_function(1); // alert 3

来源:DeluxeBlogTips

答案 1 :(得分:0)

Javascript本身可能不支持静态变量,但JS中的函数是第一类对象,因此它们可以具有可以像静态一样使用的属性。重做上面的例子:



function input_function(n) {
    alert(n + input_function.count++);
}

input_function.count = 0;

input_function(10); // alert 10
input_function(4); // alert 5
input_function(1); // alert 3




答案 2 :(得分:0)

您可以使用closure来保持功能的状态



var input_function = (function() {
  var last_argument = null;
  return function(input) {
    if (last_argument !== null && input !== last_argument + 1) { 
      throw new Error('invalid input argument: ' + input)
    }
    last_argument = input;
    console.log('input OK', input);
    // do something here?
  }
})();

input_function(4);
input_function(5);
input_function(3);