[英]How many times a function was called (even/odd number of times)
I am doing an exercise and depending on the number of times the function was called, a different result should be returned.我正在做一个练习,根据调用函数的次数,应该返回不同的结果。 If the function for example was called 0,1,2 times, it should return a number (see below), if it was called more than 3 times AND is odd (called 3 times, the third time called =odd) then it should return a string, etc. I know how I would do it if it was just called once or not at all, but I can't figure out how to write the code for odd/even times..
例如,如果函数被调用 0、1、2 次,它应该返回一个数字(见下文),如果它被调用超过 3 次并且是奇数(调用 3 次,第三次调用 =odd)那么它应该返回一个字符串等。我知道如果它只被调用一次或根本不调用我会怎么做,但我无法弄清楚如何编写奇数/偶数时间的代码..
This part was provided and should NOT be changed:这部分已提供,不应更改:
var plus = function (a,b) {
return a+b;
}
var func = sometimes(plus);
var array = [];
for(var i = 0; i < 8; i++){
array.push(func(2+i,3+i)) //should return [7,9,11, 'no idea']
}
This is the function I wrote and is clearly wrong..这是我写的函数,显然是错误的..
function sometimes (newFunc){
var called = newFunc();
if (called>4) {
return newFunc;
}
}
Not sure if this suits your issue, but give it a try running the code snippet below.不确定这是否适合您的问题,但请尝试运行下面的代码片段。
var selfInvokeFunc = (function (func) { var counter = 0; return function (func) { if (counter >= 3 && counter % 2 != 0) { counter++; return "'no idea'"; } else { counter++; return func; } } })(); var plus = function (a,b) { return a+b; } var func = function (a, b) { return selfInvokeFunc(plus(a+1,b+1)); } var array = []; for(var i = 0; i < 8; i++){ array.push(func(2+i,3+i)); } alert(array); //should return [7,9,11,'no idea',15,'no idea',19,'no idea'] document.write(array);
That should return [7,9,11,'no idea',15,'no idea',19,'no idea'] whereas那应该返回 [7,9,11,'no idea',15,'no idea',19,'no idea'] 而
array[0] = 7,数组[0] = 7,
array[1] = 9,数组[1] = 9,
array[2] = 11,数组[2] = 11,
array[3] = 'no idea', //3rd times called array[3] = 'no idea', //第三次调用
array[4] = 15,数组[4] = 15,
array[5] = 'no idea', // Odd array[5] = '不知道', // 奇数
array[6] = 19,数组[6] = 19,
array[7] = 'no idea' // Odd array[7] = 'no idea' // 奇数
Hope it answers your question.希望它能回答你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.