How to generate sequence of numbers/chars in javascript?

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

提交回复
热议问题