2016-09-10 18 views
0
function a(b) { 

var array = Array.prototype.slice.call(b); 
console.log(array); 

var array_two = ???; 
console.log(array_two); 

} 

a([1, 2, 3], 1, 2); 

console.log(array);按预期给我输出[1, 2, 3]([数字],数字)作为函数参数,如何从[]外部获取数字?

我想在这里实现[1, 2] - []之后的数字,作为数组加入。我认为b[number]会解决这个问题。 b[0] - 数组,b[1] - 数组后的第一个数字,b[2] - 数组后的第二个数字,但显然它不起作用。你知道任何解决方案吗?

+0

'VAR阵列= Array.prototype.slice.call(B);'你为什么这样做? 'b'在你传入时已经是一个数组了。看起来你想使用'arguments'对象,而不是第一个参数。 – vlaz

+2

[通过未知数量的数组参数循环]可能的重复(http://stackoverflow.com/questions/15210312/looping-through-unknown-number-of-array-arguments) –

回答

1

你可以改变你的函数

function a(array,firstArgAfterArray,secondArgAfterArray) 

,或者你可以像

arguments[1] , arguments[2] 
2

阵列时,您可以在a功能使用Rest parameter,其中...c是后得到的第一个和秒ARGS设置为a函数的最后一个参数,并且可以在a函数体内作为具有标识符c的数组访问。见What is SpreadElement in ECMAScript documentation? Is it the same as Spread operator at MDN?

function a(b, ...c) { 
 

 
var array = Array.prototype.slice.call(b); 
 
console.log(array, c); 
 
} 
 

 
console.log(
 
    a([1, 2, 3], 1, 2) 
 
    , a([1,2,3], "a", "b", "c", "d", "e", "f", "g") 
 
);

相关问题