How to generate sequence of numbers/chars in javascript?

前端 未结 18 1179
被撕碎了的回忆
被撕碎了的回忆 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:40

    If you want to produce a sequence of equal numbers, this is an elegant function to do it (solution similar to other answer):

    seq = (n, value) => Array(n).fill(value)
    

    If you want to produce a sequence of consecutive numbers, beginning with 0, this a nice oneliner:

    seq = n => n<1 ? [] : [0, ...seq(n-1).map(v => v+1)]
    

    It can easily extended for different start values and increments:

    seq = (n, start=0, inc=1) => n<1 ? [] : [start, ...seq(n-1, start, inc).map(v => v+inc)]
    
    0 讨论(0)
  • 2020-12-13 06:41

    Why not just a simple join and split?

    function seq(len, value)
    {
        // create an array
        // join it using the value we want
        // split it
        return (new Array(len + 1)).join(value).split("");
    }
    
    seq(10, "a");
    ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a"]
    
    seq(5, 1);
    ["1", "1", "1", "1", "1"]
    
    0 讨论(0)
  • 2020-12-13 06:44

    2016 - Modern Browser functionality has arrived. No need for jquery all the time.

    Array.from({length: 8}, (el, index) => 1 /* or index */);
    

    You can substitute the arrow function with a simple callback function to reach a slightly wider range of supported browsers. It's, for me at least, the easiest way to iterate over an initialized array in one step.

    Note: IE is not supported in this solution, but there is a polyfill for that at developer.mozilla.org/...

    0 讨论(0)
  • 2020-12-13 06:44

    Another method, for those how are memory saving pedant:

    Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number))
    
    0 讨论(0)
  • 2020-12-13 06:46
    for (var i=8, a=[]; i--;) a.push(1);
    
    0 讨论(0)
  • 2020-12-13 06:51

    You can make your own re-usable function I suppose, for your example:

    function makeArray(count, content) {
       var result = [];
       if(typeof content == "function") {
          for(var i = 0; i < count; i++) {
             result.push(content(i));
          }
       } else {
          for(var i = 0; i < count; i++) {
             result.push(content);
          }
       }
       return result;
    }
    

    Then you could do either of these:

    var myArray = makeArray(8, 1);
    //or something more complex, for example:
    var myArray = makeArray(8, function(i) { return i * 3; });
    

    You can give it a try here, note the above example doesn't rely on jQuery at all so you can use it without. You just don't gain anything from the library for something like this :)

    0 讨论(0)
提交回复
热议问题