0

I have an array:

var animals = ['cat', 'dog', 'horse', 'duck']

And want to pass only specified elements by index from the array (not the whole array) to a function:

function foobar(animals[1], animals[3])
{
     some function...
}

This doesn't work. The debugging tools are expecting a different syntax.

2
  • array index in function declaration? Commented Mar 3, 2012 at 17:48
  • Why was my comment asking to disregard my flag removed from this post? The flag was "declined," I left the comment specifically so that would not happen. Commented Mar 6, 2012 at 19:56

2 Answers 2

3
function foobar(a, b)
{
     some function...
}

foobar(animals[1], animals[3]);
Sign up to request clarification or add additional context in comments.

Comments

3
function foobar(animal)
{
     some function...
}

foobar(animals[1]); // send dog to foobar - js arrays start at 0

or more than one (passing an array means only one parameter needed)

function foobar(subanimals)
{
     some function... 
}

foobar([animals[1],animals[3]]); // send dog and duck to foobar as an array

Lastly if you do not want to care if you receive an array or a single item

function foobar(subanimals)
{
     if (!Array.isArray(subanimals)) subanimals=[subanimals]; //force array

     some function... 
}


foobar(animals[2]); // send ONLY horse 

Also look at array slice

In the last two functions you can do

  for (var i=0;i<subanimals.length;i++) {
    if (subanimals[i]=="duck") alert("fowl");
    else if (subanimals[i]=="horse") alert("ungulate");
    else alert("Neither fowl nor horse");
  }

1 Comment

Thanks! On your example 2, how do I work inside the function with dog and duck if I don't know that the values are dog and duck? The array is dynamically generated on page load, in reality I don't know the value names, yet still need to use them in the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.