在javascript

时间:2016-03-14 20:45:54

标签: javascript arrays function parsing element

我试图从另一个函数解析一个数组。 我在其他帖子中看到" .apply"可以在这个例子中使用:

var x = [ 'p0', 'p1', 'p2' ]; 
call_me.apply(this, x);

但是在我的代码中我想解析其他函数而不仅仅是一个数组,我想要解析数组和两个字符串。所以mi代码看起来更像:

var array = [1, 2, 3];
var string = "something":
var string1 = "something":
ShowM(array, string, string2);

function ShowM(array, string1, string2) {
alert(array[1] + string1 + string2);
}

有没有办法在不改变数组元素的原始位置的情况下做到这一点,以免未定义? Thnks

2 个答案:

答案 0 :(得分:1)

如果问题纯粹是关于如何在主题问题中将数组设置为Javascript中的参数,那么您就像其他任何变量一样。

var array = [a,b,c];
var str = "hello";
var str2 = "something";

function foo(x,y,z) {
    // do stuff...
}

foo(array, str, str2); //executes function with the 3 parameters

答案 1 :(得分:0)

如果您只想将数组传递给函数,可以像传递任何其他变量一样传递它:

function showM(a, b, c) {
    // empty function definition
}

var x = [ 'p0', 'p1', 'p2' ];
showM(x, "some string", "another string");

所有数组都是通过javascript中的引用传递的,因此当您在函数中更改传递的数组内容时,内容将在所有范围内更改。而duck-typing意味着你可以使用任何变量类型作为参数。

另一方面,apply函数调用具有给定内容和参数数组的函数(它扩展,与ES6扩展运算符一样):

// equivalent to the other call, except "this" is bound to null
showM.apply(null, [x, "some string", "another string"]);