views:

56

answers:

3

Hi,

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?

Thank you

+5  A: 

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

Nick Craver
@Nick, i think `result.push(i);` should be ` result.push(content);` ahh... edited already..
Gaby
@Gaby - Yup, noticed that when I setup the demo, thanks :)
Nick Craver
Hey, thanks for this. Thought there could be something similar to what's available in MatLab, i.e. create vector of some length that will contain certain elements.
vikp
+1  A: 
for (var i=8, a=[]; i--;) a.push(1);
no
not enough jQuery =)
Ninja Dude
needs moar jquery? hmmm, does this work: `for (var i=8, a=[]; i--;) a.push($(1));`
no
@no just kidding, OP may not be satisfied, 'cause it is missing jQuery, lol. In your comment `a.push($(1))`, it pushes jQuery objects into the array not the numbers :)
Ninja Dude
@Avinash, I know, was just screwing around ;)
no
A: 
The fastest way to define an array of 8 1s is to define it-
var A= [1, 1, 1, 1, 1, 1, 1, 1];

// You'd have to need a lot of 1s to make a dedicated function worthwhile.

// Maybe in the Matrix, when you want a lot of Smiths:

Array.repeat= function(val, len){
    for(var i= len, a= []; i--; ) a[i]= val;
    return a;
}
var A= Array.repeat('Smith',100)

/*  returned value: (String)
Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith
*/
kennebec