I’m trying to set up an array through jQuery’s .each() function, but it seems like I’m not properly doing it?
I have attributes in the html such as:
<div class="cheers" data-fname = "fname" data-lname="lname">some ish..</div><!-- going through a while loop!-->
Then I have a jquery function that does something like this
var arrayMe = [];
$(".cheers").each(function(index){
arrayMe[index] = $(".cheers").attr('data-fname')+","+$(".cheers").attr('data-lname');
});
Then, when I try to do various alerts:
alert(arrayMe); //this gives me the fname,lname
alert(arrayMe[0]); //this gives me the first fname,lname in the array
alert(arrayMe[0][1]); //this SUPPOSED to give me the first lname, but it gives me a letter...
You have to use
arrayMe[1]instead ofarrayMe[0][1].You get a letter, because
arrayMe[0]is a string, andarrayMe[0][1]retrieves the second character of the given string. It’s equivalent toarrayMe[0].charAt(1).If you want to build a 2D array, use:
(I have also fixed another issue in your code by replacing
$('.cheers')with$(this))