How to generate sequence of numbers/chars in javascript?

前端 未结 18 1197
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 06:22

Is there a way to generate sequence of characters or numbers in javascript?

For example, I want to create array that contains eight 1s. I can do it with for loop, bu

18条回答
  •  情话喂你
    2020-12-13 06:37

    A sequence is a stream, which computes the value when it is needed. This requires only a bit memory but more CPU time when the values is used.

    An array is a list of precomputed values. This takes some time before the first value can be used. And it requires much memory, because all possible values of the sequence must be stored in memory. And you have to define an upper limit.

    This means, that in most cases it is no good idea to create an array with sequence values. Instead it is better to implement the sequence as a real sequence, which is limited just by the word length of the CPU.

    function make_sequence (value, increment)
    {
      if (!value) value = 0;
      if (!increment) increment = function (value) { return value + 1; };
    
      return function () {
        let current = value;
        value = increment (value);
        return current;
      };
    }
    
    i = make_sequence()
    i() => 0
    i() => 1
    i() => 2
    
    j = make_sequence(1, function(x) { return x * 2; })
    j() => 1
    j() => 2
    j() => 4
    j() => 8
    

提交回复
热议问题