简体   繁体   English

在JavaScript中将数组作为参数传递

[英]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. 我得到的arrayP [0]是未定义的,这可能是真的,因为在函数内部我从来没有写过什么样的数组arrayP。 So, 所以,

  1. Is is possible to pass arrays as parameters? 是否可以将数组作为参数传递?
  2. If so, which are the requirements inside the function? 如果是这样,功能内部的要求是什么?

Just remove the .value , like this: 只需删除.value ,如下所示:

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. 当然你可以传递一个数组,但要在该位置获取元素, 使用arrayName[index] .value value将从数组中该位置的对象获取value属性 - 对于像字符串,数字这样的东西,等不存在。 For example, "myString".value would also be undefined . 例如, "myString".value也将是undefined

JavaScript is a dynamically typed language. JavaScript是一种动态类型语言。 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. 因此,只要arrayP是一个数组并且包含具有value属性的元素,您的代码就会起作用。

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] ? 你确定要传递给函数的数组实际上有一个元素在[0]吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM