How to generate sequence of numbers/chars in javascript?

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, but wondering whether there is a jQuery library or javascript function that can do it for me?


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 :)


Without a for loop, here is a solution:

Array.apply(0, Array(8)).map(function() { return 1; })

The explanation follows.

Array(8) produces a sparse array with 8 elements, all undefined . The apply trick will turn it into a dense array. Finally, with map , we replace that undefined the (same) value of 1 .


for (var i=8, a=[]; i--;) a.push(1);
链接地址: http://www.djcxy.com/p/17688.html

上一篇: 为什么这个函数执行两次?

下一篇: 如何在JavaScript中生成数字/字符序列?