开发者

Is there any math. function which gives sequence of numbers when ever i call it?

I have the following function:

function random()
{

    var whichProduct = Math.floor(Math.random()*5);

    UIALogger.logMessage(whichProduct);
}
random();

This will give a random number in [1,4] whenever i call this function.

I want to know whether there 开发者_JS百科is any other function which will give me a sequence of numbers in order (like: 1, 2, 3, 4, 5) when I call it.


Use closure, here is a simple example: Each time you call x() it returns the next number in the sequence(starting at 'startVal'), but it does not compute every number in advance, only when it is called.

function seq(startVal) {  
   var i = startVal - 1;
   return function() {
      return i++;
   }
}
x = seq(1);
alert(x()); // alert(1)
alert(x()); // alert(2)
alert(x()); // alert(3)

Edit: Made a simple adjustment to pass in a starting value, sequence will begin there.


I don't think there is anything built in to the language but you can define your own like so:

var increasingSequence = function(a, b) {
  var seq=[], min=Math.min(a,b), max=Math.max(a,b), i;
  for (i=min; i<max; i++) {
    seq.push(i);
  }
  return seq;
};
increasingSequence(1, 5); // => [1, 2, 3, 4, 5]
increasingSequence(2, -2); // => [-2, -1, 0, 1, 2]

Note also that Math.random() returns a value in the range [0,1) (that is including zero but not including one), so if you want your random function to return [1,5] then you should implement it like so:

Math.floor(Math.random() * 5) + 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜