Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic array (try 2)

Status
Not open for further replies.

SirEddy

Programmer
Oct 24, 2005
10
US
I am a bit lost here and think I did something like this in the past. Say I have array that I want to call the record length as follows:

dataRecords = data_fish.length
or
dataRecords = data_dogs.length
where data_fish and data_dogs are the arrays

But I want to have a function to dynamicaly call the length for example but want to use variables like:

recordCatagory = fish
getLength(recordCatagory)

or

recordCatagory = dogs
getLength(recordCatagory)

function getLength(recordCatagory) {
arrayToCall= "data_" + recordCatagory
dataRecords = arrayToCall.length
}

Is it possible?
 
Yes, it's possible, but if you use that technique a lot, it will be slower than the less complicated method you're familiar with already:

Code:
getLength('dogs');
getlength('fish');

function getLength(recordCatagory)
{
var arrayToCall = eval("data_" + recordCatagory);
return arrayToCall.length;
}

eval() is quite expensive in clock cycles, and generally not recommended.

Lee

 
SirEddy, do you NEED to build the array name in the function or can you pass it in complete?

If you have the array declared data_dogs and you pass data_dogs into the function you actually pass the reference of the array, not just text so it will work directly when you test it's length.

Here is an example:
Code:
<HTML>
<HEAD>
<TITLE>Dynamic Option List</TITLE>
<SCRIPT language="javascript">
var data_dogs = new Array('First','Second','Third','Fourth');
var data_fish = new Array('Uno','Dos','Tres');

function getLength(recordCatagory) {
    dataRecords = recordCatagory.length
}
</SCRIPT>
</HEAD>
<BODY>
<input type="button" name="dogs" value="Dogs" onclick="getLength(data_dogs)"><br>
<input type="button" name="fish" value="Fish" onclick="getLength(data_fish)"><br>
</BODY>
</HTML>

Paranoid? ME?? WHO WANTS TO KNOW????
 
You could also do this:
Code:
function getLength(recordCatagory) {
    dataRecords = window["data_" + recordCatagory].length;
}
Or
Code:
function getLength(recordCatagory) {
    return window["data_" + recordCatagory].length;
}
See faq216-3858 for more info.

Adam
 
I just realized that "Catagory" is a misspelling. Just copied and pasted what was originally written.

I'd go with adam0101's solution. I thought of that after I shut down my computer last night, but forgot about it until I saw it above.

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top