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); gives me output [1, 2, 3] as expected.

What I want to achieve here is getting [1, 2] - numbers after [ ], joined as array. I thought that b[number] would solve the problem. b[0] - array, b[1] - first number after array, b[2] - second number after array but apparently it does not work like that. Do you know any solution for that?

dddeee
  • 237
  • 4
  • 12
  • `var array = Array.prototype.slice.call(b);` why do you do this? `b` is already an array when you pass it in. It seems like you wanted to use the `arguments` object, not the first parameter. – VLAZ Sep 10 '16 at 19:04
  • 2
    Possible duplicate of [Looping through unknown number of array arguments](http://stackoverflow.com/questions/15210312/looping-through-unknown-number-of-array-arguments) – t.niese Sep 10 '16 at 19:05

3 Answers3

2

You can use Rest parameter at a function, where ...c is set as last parameter to a function, and can be accessed within a function body as an array having identifier c. See 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")
);
Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
1

you can either change your function to

function a(array,firstArgAfterArray,secondArgAfterArray)

or you can get the first and seconds args after the array like that

arguments[1] , arguments[2]
naortor
  • 2,019
  • 12
  • 26
1

You can achieve all given parameters as an array with the predefined variable arguments. But in this case you have to remove the first element (because its array_one):

var array_two = Array.prototype.slice.call(arguments, 1);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

Martin Wantke
  • 4,287
  • 33
  • 21