1

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         }  
3
  • what's the problem with this? Any error messages? Commented May 27, 2012 at 8:32
  • Your code, here, looks fine. Did you check whether and cellHeight, cellWidth are correctly defined? How, exactly, does it fail? Commented May 27, 2012 at 8:33
  • Uncaught TypeError: Cannot set property '0' of undefined is the error I get. I get the same error if I try a = [[]]; a[1][22] = "test"; however b = [];b[22] = "test"; yields [,,,,,,,,,,,,,,,,,,,,,,"test"]. the other two properties all work fine. I think it's an issue with how javascript handles nested arrays. If that's the case I'm more interested in a workaround than a solution to the problem. Commented May 27, 2012 at 8:52

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that set me on the right track. I ended up using if(!cellLookup[arrayX]){ cellLookup[arrayX] = []}; if(!cellLookup[arrayX][arrayY]){ cellLookup[arrayX][arrayY] = []};cellLookup[arrayX][arrayY] = arrayValue; to fix it.

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.