简体   繁体   中英

How do I create a sparse array in javascript through iteration?

I wrote this code to scrape a sparse array from a series of dom elements. when done in one dimension the code works but in 2 dimensions it fails. Is there something i'm missing?

23         function initCellHover(){
24                 $cells.each(function(){
25                         var arrayX = $(this).position().left/cellWidth;
26                         var arrayY = $(this).position().top/cellHeight;
27                         var arrayValue = $(this);
28                         cellLookup[arrayX][arrayY] = arrayValue;
29                 });     
30         }  

In line 28 you may be referring to a property of undefined. It makes sense to check, if there already is a property in the array and add it, if needed:

cellLookup[arrayX] = cellLookup[arrayX] || [];
cellLookup[arrayX][arrayY] = arrayValue;

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