有没有数学.当我调用它时给出数字序列的函数? [英] Is there any math. function which gives sequence of numbers when ever i call it?

查看:35
本文介绍了有没有数学.当我调用它时给出数字序列的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

function random()
{

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

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

每当我调用此函数时,这将在 [1,4] 中给出一个随机数.

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

我想知道是否有任何其他函数可以在我调用它时按顺序为我提供一系列数字(例如:1、2、3、4、5).

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

推荐答案

使用闭包,这里是一个简单的例子:每次调用 x() 时,它都会返回 中的下一个数字序列(从'startVal'开始),但它不会提前计算每个数字,只有在调用时才计算.

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)

做了一个简单的调整以传入一个起始值,序列将从那里开始.

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

这篇关于有没有数学.当我调用它时给出数字序列的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆