26

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?
1

3 Answers 3

37

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.

Sign up to request clarification or add additional context in comments.

2 Comments

String.prototype.value = "Hi Nick I broke your example!" /evil codez don't use
@IvoWetzel Why do you considered it as evil code? Is the code that he provided vulnerable?
5

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.

Comments

2

It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]?

Comments

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.