Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array as parameter in JavaScript

I have an array, and I want to pass it as a parameter in a function such as:

function something(arrayP){     for(var i = 0; i < arrayP.length; i++){           alert(arrayP[i].value);     }  } 

I'm getting that arrayP[0] is undefined, which might be true as inside the function I never wrote what kind of array arrayP is. So,

  1. Is is possible to pass arrays as parameters?
  2. If so, which are the requirements inside the function?
like image 540
Gabriel Avatar asked Dec 18 '10 19:12

Gabriel


People also ask

Can you pass an array as a parameter in JavaScript?

As such, Javascript provides us with two ways to use arrays as function parameters in Javascript - apply() and the spread operator.

Can you pass an array as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

What is an array argument in JavaScript?

arguments is an Array -like object accessible inside functions that contains the values of the arguments passed to that function.


2 Answers

Just remove the .value, like this:

function(arrayP){        for(var i = 0; i < arrayP.length; i++){       alert(arrayP[i]);    //no .value here    } } 

Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

like image 197
Nick Craver Avatar answered Oct 07 '22 08:10

Nick Craver


JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

like image 32
Amnon Avatar answered Oct 07 '22 08:10

Amnon