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));
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
Share Improve this question asked Feb 1, 2016 at 21:25 Lucky500Lucky500 5076 gold badges17 silver badges34 bronze badges 2- stackoverflow./questions/2141520/… 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 w3schools./jsref/jsref_push.asp - here is how to push elements to a javascript array. – Rafael Korbas Commented Feb 1, 2016 at 21:29
- 3 Start with MDN; you have a problem on nearly every line here. – Evan Davis Commented Feb 1, 2016 at 21:29
4 Answers
Reset to default 3This will get those numbers into the array for you. And it will do it for unlimited numbers supplied: https://jsfiddle/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));
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;
}
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]));
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>');