1

I have an array of months like this:

var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];

What i am trying to do is make the name of the month a variable and set an object to it like so:

for(i=0;i<11;i++){
months[i] = $(".bitem:eq("+i+")");
}

But that just replaces months[i] (if i=0 for example it would replace "jan" with the object). What i want to do is use the string that months[i] is equal to for the variable name. I tried using .toString() like this:

for(i=0;i<11;i++){
months[i].toString() = $(".bitem:eq("+i+")");
}

but I get the error:

Error: ReferenceError: invalid assignment left-hand side
6
  • Are you trying to set the text of .bitem elements to corresponding months? Commented Aug 5, 2012 at 20:43
  • Do you want to generate var jan = ... dynamically? Commented Aug 5, 2012 at 20:48
  • My guess is you a) misuse classnames when you want IDs and b) want to add a .text() to your code and c) need to remove the toString from the left side of the equals like months[i] = $(".bitem:eq("+i+")").text(); Commented Aug 5, 2012 at 20:48
  • What do you need it for? Almost every time someone ask how to create variables dynamically, there is a much better solution for what they really want to accomplish. Commented Aug 5, 2012 at 20:56
  • @Guffa Yes, the better solution was provided below. Commented Aug 5, 2012 at 20:57

2 Answers 2

4

Why exactly do you need to have variables names jan, feb, etc? From what I can tell, you can do everything you want by using a plain old object with properties:

var monthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];

var months = {};
for(var i = 0; i < monthNames.length; i++) {
    months[monthNames[i]] = $(".bitem:eq("+i+")");
}

// Example usage
var januaryItem = months["jan"];
// or equivalent: months.jan;
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfect! Thank you. I tried something similar but I've been working at this so long I couldn't think clearly. Thanks again.
1

Instead of creating variables, make an object that can translate the string to the index in the array:

var monthIndex = {
  "jan": 0, "feb": 1, "mar": 2, "apr": 3, "may": 4, "jun": 5,
  "jul": 6, "aug": 7, "sep": 8, "oct": 9, "nov": 10, "dec": 11
};
var months = $(".bitem");

Now given any of the month names, you can get the corresponding element from the array:

var m = 'aug';
var element = months[monthIndex[m]];

You can also use specific month names to get the index:

var element = months[monthIndex.aug];

1 Comment

Of course, jQuery collections are array-like, how could I forget! You can do everything with one DOM query and you even get rid of the loop. Great work! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.