Javascript loops

I have an array in javascript with the following data to be populated in a div. The array is as follows

var array1 = new array('abc','def', 'ghi', 'jkl','mno'); 

I want to implement pagination for a div containing a set of divs holding each with data from the specified array. that is, div 1 will contain abc, div 2 will contain def, etc ...

I send the page without a click and the maximum number of divs that will be displayed on the page for the function. I set max_num divs to display is 2. The function is as follows.

 function renderPagination(pageno, max_num){ for(var i=0;i< max_num; i++){ } } 

Here I need to run a loop in which a lot of divs will be populated. those. if pageno is '0', you should see abc, def divs. If pageno is "1", then div ghi, jkl should be displayed. I think, instead of i = 0, I should initialize another variable.

+4
source share
3 answers

Use Array.Slice

 function renderPagination(pageno, max_num) { return array1.slice( (pageno - 1) * max_num, pageno * max_num ); } 

Demo here: http://jsfiddle.net/naveen/Ctp99/

On the unrelated side, an Array note should be new Array() , not new Array()

+7
source

If you ask how to initialize i, I suppose you mean:

 for(var i=pageno*max_num;i< max_num; i++){ } 

Assuming pageno starts at 0, according to your text.

0
source
 var array1 = ['abc','def', 'ghi', 'jkl','mno']; function renderPagination(pageno, max_num){ max_num += pageno; // max_num will be max_num + pageno // make sure max_num will not go out of bounds if(max_num > array1.length){ max_num = array1.length; } for(pageno; pageno < max_num; pageno++){ console.log(array1[pageno]); } } renderPagination(1, 2); 

See demo

With this solution, no matter where your page starts or what max_num will be, it will always return the correct pages and never go out of the array.

0
source

All Articles