Question

i want use some arrays as function parameters. i write this code but doesn't work. please help me

and i have no idea about number of array

function func2(x,y,z)
{
    alert(x[1]);
    alert(y[1]);
    alert(z[1]);

}
function func1()
{
    a = [1,2,3]
    b = [3,4,5]
    c = [5,6,7]
    func2(a,b,c);
}
Was it helpful?

Solution

Your func2 function is calling itself. Also, using var is a good idea here to avoid accidentally creating global variables:

function func2()
{
    var a = [1,2,3],
        b = [3,4,5],
        c = [5,6,7];
    func1(a,b,c);
}

Update given your updated question, if you want to create a function that accepts a variable number of parameters, you'll need to access the arguments object:

function func2()
{
    alert("There are " + arguments.length + " arguments");
}

The arguments object is can be accessed just like an array (although it is not actually an array). So to print the second element from each array (remember array indexes start at 0), you'd use something like this:

function func2()
{
    for (var i = 0; i < arguments.length; i++)
        alert(arguments[i][1]);
}

An alternate strategy would be to just accept an array of arrays (also called a multidimensional array, though technically multidimensional arrays aren't supported in JavaScript) like this:

function func2(a)
{
    for (var i = 0; i < a.length; i++)
        alert(a[i][1]);
}
function func1()
{
    var a = [1,2,3],
        b = [3,4,5],
        c = [5,6,7];
    func2([a,b,c]);   // notice the […] around the parameters
}

OTHER TIPS

function func1(x,y,z)
{
    alert(x[1]);
    alert(y[1]);
    alert(z[1]);
}
function func2()
{
    var a = [1,2,3];
    var b = [3,4,5];
    var c = [5,6,7];
    func1(a,b,c);
}

If I read you minds well, you have to use arguments in order to iterate over a dynamic number of arguments. Assuming you pass only arrays to func2:

function func2() {
    for (var i = 0; i < arguments.length; i++) {
        alert(arguments[i][1]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top