1

Trying to do something simple, but not sure what I am doing wrong.

I simply want to call a function with number arguments and push those numbers into a new array...

function someFunction(n){
  var newArray = new Array(n);
  for(var i=0; i < n.length; i++){
    newArray += n[i];
  }
  return newArray;
}

console.log(someFunction(3,5,4,5));

Here is bin

Lucky500
  • 677
  • 5
  • 17
  • 31
  • http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function take a look at this - here is explained how to deal with a variable number of arguments, which is, if I understand good, your main issue. And also at this http://www.w3schools.com/jsref/jsref_push.asp - here is how to push elements to a javascript array. – Rafael Korbas Feb 01 '16 at 21:29
  • 3
    Start with MDN; you have a problem on nearly every line here. – Evan Davis Feb 01 '16 at 21:29

4 Answers4

3

This will get those numbers into the array for you. And it will do it for unlimited numbers supplied: https://jsfiddle.net/a9umss9a/3/

function someFunction(){
  var newArray = [];
  for(var i=0; i < arguments.length; i++){
    newArray.push(arguments[i]);
  }
  return newArray;
}

console.log(someFunction(3,5,4,5));

console.log(someFunction(3,5,4,5,100,200,300,400,500));
gfrobenius
  • 3,987
  • 8
  • 34
  • 66
2

You can do this as a one-liner:

function toArray() {
    return [].slice.call(arguments);
}

Here's the breakdown of issues in your code.

function someFunction(n){ // this captures the FIRST argument as n
  var newArray = new Array(n); // this creates a new Array of length n (in your case, 3, which is not accurate
  for(var i=0; i < n.length; i++){ // n is a number and has no length property
    newArray += n[i]; // newArray is an array, so you must push to it; the + operator makes no sense
  }
  return newArray;
}
Evan Davis
  • 35,493
  • 6
  • 50
  • 57
0

someFunction requires 1 input of type array, not 4 inputs:

function someFunction(n){
  var newArray = [];
  for(var i=0; i < n.length; i++){
    newArray.push(n[i]);
  }
  return newArray;
}

console.log(someFunction([3,5,4,5]));
Jacob Petersen
  • 1,463
  • 1
  • 9
  • 17
  • True. But doing it this way makes the function pointless. You could just replace the guts of the function with `function someFunction(n){ return n; }` and get the same thing. The OP wanted this format: `someFunction(3,5,4,5)`. – gfrobenius Feb 01 '16 at 21:37
0

A solution with direct building of an array.

function someFunction() {
    return Array.apply(null, arguments);
}

document.write('<pre>' + JSON.stringify(someFunction(3, 5, 4, 5), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392