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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4479581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:35:31  来源:igfitidea点击:

Passing an array as parameter in JavaScript

javascriptarrays

提问by Gabriel A. Zorrilla

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,

我得到 arrayP[0] 未定义,这可能是真的,因为在函数内部我从未写过 arrayP 是什么类型的数组。所以,

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

回答by Nick Craver

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 onlyarrayName[index], the .valuewould be getting the valueproperty off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".valuewould also be undefined.

当然你可以传递一个数组,但是要在那个位置获取元素,使用arrayName[index],这.value将从value数组中那个位置的对象中获取属性 - 对于字符串,数字等不存在的东西。例如,"myString".value也将是undefined

回答by Amnon

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 arrayPis an array and contains elements with a valueproperty.

JavaScript 是一种动态类型语言。这意味着您永远不需要声明函数参数(或任何其他变量)的类型。因此,只要您的代码arrayP是一个数组并且包含具有value属性的元素,您的代码就可以工作。

回答by ClosureCowboy

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]吗?