简体   繁体   中英

jQuery two column (one dimensional) array?

I have a simple one dimensional array but I want to split the long list into two columns using jQuery. How can I achieve this?

var articles = ['article10','article9','article8','article7','article6','article5','article4','article3', 'article2', 'article1'];
for ( var articCounter = articles.length; articCounter > 0; articCounter--) {
    document.write('<a href="../articles/' + articles[articCounter-1] + '.pdf" > ' + articles[articCounter-1] + '</a></br>');  
} // end for

I don't want to have to create two different arrays for two different float divs.... I've googled this many times but many other methods deal with multidimensional arrays.

Thank you very much for the help in advance.

EDIT: Right now it's just one long list like so:

Article1
Article2
Article3
....

But I would like to achieve this:
在此处输入图片说明

This will split your array into 2 arrays:

var articles = ["article1", "article2", "article3", "article4", "article5", "article6", "article7", "article8", "article9", "article10"];   
var separatorIndex = articles.length & 0x1 ? (articles.length+1)/2 : articles.length/2;

var firstChunk = articles.slice(0,separatorIndex); 
//["article1", "article2", "article3", "article4", "article5"] 
var secondChunk = articles.slice(separatorIndex,articles.length); 
//["article6", "article7", "article8", "article9", "article10"] 

Then you can use them where and/or how you want.

Explanation

The 2nd line finds an anchor index (alias -> middle index of division),by which array should be divided into 2 chunks. The array can have odd and even lengths,and those 2 situations must be distinguished. As it is impossible to divide odd-length array into 2 equal parts, it must be divided in such way, that 1st chunk will have 1 element more or less ,than 2nd chunk.Here, I have implemented first case,that is, 1st chunk will have 1 element more,than 2nd one. Here are the examples of different situations:

total length | 1st (length) | 2st (length) | separatorIndex 
    10            0-4 (5)        5-9 (5)          5        
    11            0-5 (6)       6-10 (5)          6
    12            0-5 (6)       0-11 (6)          6

In table, number - number syntax shows accordingly start and end indexes in array. The division is done by .slice() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM