I am using jQuery 1.7.1 (but that’s probably irrelevant).
I have several JavaScript arrays that are populated in several ways. The arrays, basically, look like this:
var TreeArray = [0,1,2];
var FruitArray = [4,5,6,7];
I have some links that have an item type and an item id:
<a href='?' class='Link' data-itemid='123' data-itemtype='Tree'>elm</a>
<a href='?' class='Link' data-itemid='789' data-itemtype='Tree'>walnut</a>
<a href='?' class='Link' data-itemid='456' data-itemtype='Fruit'>orange</a>
<a href='?' class='Link' data-itemid='111' data-itemtype='Fruit'>apple</a>
When the link is clicked, the ItemType and ItemID are collected and passed to the addToArray() function:
$Links.click(function(e) {
e.preventDefault();
var ItemType = $(this).data("itemtype");
var ItemID = $(this).data("itemid");
addToArray(ItemType, ItemID);
});
Here’s where the problem is. If the ItemType is “Tree”, I want to put the ItemID in the TreeArray. If the ItemType is “Fruit”, I want to put the ItemID in the FruitArray. Here’s my function (that doesn’t work):
var addToArray = function addToArray(ItemType, ItemID) {
var WhichArray = ItemType + "Array";
WhichArray.push[ItemID];
}
I will have quite a few different types of arrays, not just two. I will have quite a few functions.
So, how can I access these arrays dynamically?
Change your arrays to be properties of an object and then you can access them dynamically by name:
As an alternative, if
TreeArrayandFruitArraywere global variables, you could also access them off thewindowobject like this without changing the array definitions, though I prefer the first implementation above:This works because all global variables are implicitly properties of the window object.