By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,568 Members | 1,196 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,568 IT Pros & Developers. It's quick & easy.

function to execute all functions listed in an array

P: n/a
I am trying to create a function that executes all the functions listed
in an array. I cannot get it to work.

<html>
<body>
<script language="JavaScript">

var length_of_array = 2;
var function_array = new Array(
"no1()",
"no2()",
length_of_array);

function main_function(cat, cow)
{
for(var x = 0; x<cow; x++)
{
cat[x];
}
}

function no1()
{
alert("hello");
}

function no2()
{
alert("good bye");
}

</script>
<input type="button" value="click"
onClick="main_function(function_array, length_of_array)">
</body>
</html>

Your help will be appreciated.

Bundy
Aug 24 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a


Bundy wrote:
I am trying to create a function that executes all the functions listed
in an array. I cannot get it to work.
var function_array = new Array(
"no1()",
"no2()",
You have strings in that array, not functions. If you want to have
functions in the array then simply like this
var function_array = [no1, no2];
or
var function_array = new Array(no1, no2);
function no1()
{
alert("hello");
}

--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 24 '06 #2

P: n/a
Bundy <bi*******************@vfemail.netwrites:
I am trying to create a function that executes all the functions
listed in an array.
<script language="JavaScript">
(invalid HTML 4, should be, e.g., <script type="text/javascript">)
var length_of_array = 2;
var function_array = new Array(
"no1()",
"no2()",
length_of_array);
Why store code in the array, and not the functions themselves?
And why store the length of the array? Arrays are quite capable
of knowing their own length.

I suggest doing:
---
var function_array = new Array(no1, no2);

function main_function(cat, cow) {
for(var x = 0; x < cat.length; x++) {
(cat[x])();
}
}
....
onclick="main_function(function_array);"
---

Using references to the functions themselves obviously requires them
to be defined at the point the array is created. That means that the
functions should be defined in the same script element as the array,
or in previously executed script element.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 24 '06 #3

P: n/a
var a=function(){alert("a")}
,b=function(){alert("b")}
,c=function(){alert("c")}
,d=function(){alert("d")}
,arr=[a,b,c,d]

for(var i in arr){
arr[i]()
}

*** Sent via Developersdex http://www.developersdex.com ***
Aug 24 '06 #4

P: n/a
Thank you to you both.

Bundy
Aug 24 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.