4

I am trying to create an array in jQuery, which is filled through a loop.

count = jQuery('#count_images').val();

With the above code I get an integer value (such as 5, for example). What I would like to know, is how I can do something like this in jQuery:

int arrLength = count;
string[] arr1 = new string[arrLength];
int i = 0;
for (i = 0; i < arr1.Length; i++){
    arr1[i] = i;
}

So in the end my array for example 5 would look like this: [1,2,3,4,5].

2
  • did you try looking at api.jquery.com/jQuery.each Commented Apr 20, 2012 at 8:21
  • I did, but that was not what I was looking for though. Anyways, I used dknaack's solution, and that works fine for me. Thanks anyways. Commented Apr 20, 2012 at 8:57

6 Answers 6

10

Description

This is more about javascript and not jquery. Check out my sample and this jsFiddle Demonstration

Sample

var arrLength = 5;
var arr1 = [];
var i = 0;

for (i = 0; i != arrLength; i++){
  arr1.push(i)
}

alert(arr1.length)

More Information

Sign up to request clarification or add additional context in comments.

Comments

0

firstly, val() will return a string, so parse it to an integer

var count = parseInt(jQuery('#count_images').val(),10);

Then you can simply use a loop to create your array:

var arr = [];
for(var i=0;i<count;i++){
   arr.push(i);
}

This would create an array with values [0,1,2,3,4], if you want it to start at 1 just add 1 to the i

var arr = [];
for(var i=0;i<count;i++){
   arr.push(i+1);
}

Comments

0

Something like this should suffice:

var my_array = [];
var count = 5;      // let's assume 5

for(var i=0; i < count; i++) {
    my_array.push(i);
}

Comments

0

There is no special way for this in jQuery. It's the simpliest way:

arr1 = []; 
for (var i = 0; i < count; i++) arr1[i] = i + 1;
// arr1 = [1, 2, 3, 4, 5]

Comments

0
var days = $.map(new Array(31), function(item, index){return index+1;});

Comments

0
$(".chk-individual-vendor").each(function() {
    var arrVendors = [];
    arrVendors.push($(this).attr('vendor-user-id'));    
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.