1

i want to loop a jquery selector using .each() and assign values to a multidimensional array $record. here is what i tried and it doesnt work

JQUERY:

var $record = new Array(),
    i=0,
    x,y;
$("td").each(function(){       
    x = Math.floor((i+1)/4),
    y = i%4;
    $record[x][y] = true;    
    i++;
});

CHROME CONSOLE ERROR: Uncaught TypeError: Cannot set property '0' of undefined

1
  • That is one strange looking array, can't imagine how you'd access that and figure out the keys ? Commented Apr 26, 2014 at 16:51

2 Answers 2

1

That error is raising because you did not define the inner array.

Try,

$("td").each(function(){       
    x = Math.floor((i+1)/4),
    y = i%4;
    if(!$.isArray($record[x])) { $record[x] = []; }
    $record[x][y] = true;    
    i++;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Consider this

var record = [],
    i = 0,
    x = Math.floor((i+1)/4),
    y = Math.floor((i+1)/4)

console.log(record); // 0
console.log(record[0]); // undefined
console.log(record[x][y]); // Uncaught TypeError: 
                           // Cannot read property '0' of undefined 

First iteration, i is 0. You're trying to access an element that doesn't exist. Or to be even more specific, the property 0 on the array, which would exist if there was an element on index 0.

In other words, if you add something to the array, it would get it's property:

record[0] = 'something';
console.log(record['0'], record.hasOwnProperty('0')); // 'something', true

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.