function to execute all functions listed in an array

B

Bundy

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
 
M

Martin Honnen

Bundy said:
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);
 
L

Lasse Reichstein Nielsen

Bundy said:
I am trying to create a function that executes all the functions
listed in an array.
<script language="JavaScript">

(invalid HTML 4 said:
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
 
V

Val Polyakh

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()
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top