javascript:将数组传递给函数 [英] javascript: pass an array to a function
问题描述
这里是我的javascript代码:
var my_array = new Array();
my_array [0] =a;
my_array [0] =b;
my_array [0] =c;
print_array(my_array);
函数print_array(arr)
{
alert(arr);
}
但它不起作用,因为我无法将数组传递给功能。那么,我该如何将整个数组传递给javascript函数呢?
编辑:
Nevermind。我发现了这个解决方案。
隐藏的原因是不好的做法,并将数组作为字符串传递:
如果有人需要将数组传递给函数,请首先使用:JSON.stringify()和javascript将能够解析数组。
解决方案问题在于你正在为每个元素分配索引
0
,所以它们相互覆盖。 / p>
//应该是
my_array [0] =a;
my_array [1] =b;
my_array [2] =c;
//或者,如果您不想跟踪索引
my_array.push(a);
my_array.push(b);
my_array.push(c);
其余代码看起来很好。您可以将整个数组或任何对象以这种方式传递给函数。
当您提醒它时,javascript将连接数组转换为逗号分隔的字符串以便查看。
here is my javascript code:
var my_array = new Array(); my_array[0] = "a"; my_array[0] = "b"; my_array[0] = "c"; print_array(my_array); function print_array(arr) { alert(arr); }
But it doesn't work, because I can't pass the array to the function. So, how can I pass an entire array to javascript function?
EDIT: Nevermind. I found the solution.
Hidden cause this is bad practice and passes the array as a string:If someone will need to pass an array to the function, first use this: JSON.stringify() and javascript will be able to parse an array.
解决方案The problem is you are assigning each element to index
0
, so they are overwriting each other.// should be my_array[0] = "a"; my_array[1] = "b"; my_array[2] = "c"; // alternatively, if you don't want to track the index my_array.push("a"); my_array.push("b"); my_array.push("c");
The rest of the code looks fine. You can pass whole arrays, or any object for that matter to a function in exactly the manner you have shown in your code.
When you alert it, javascript will concatenate the array into a comma separated string for easy viewing.
这篇关于javascript:将数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!