2016-02-01 73 views
0

试图做一些简单的事情,但不知道我做错了什么。将数字推入数组

我只是想打电话与数量参数的功能,推动这些数字到一个新的数组...

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));

这里是bin

+0

http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function看看这个 - 在这里解释如何应对可变数量的参数,如果我理解的话,就是你的主要问题。而且在这个http://www.w3schools.com/jsref/jsref_push.asp - 这里是如何将元素推送到一个javascript数组。 –

+3

以MDN开头;你几乎在每一行都有问题。 – Mathletics

回答

2

这将让这些数字进入你的阵列。并且它将做它提供无限数量: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)); 
+0

谢谢gfrobenius,那就是我一直在寻找的。 – Lucky500

+0

如果你不使用它,为什么要命名为arg'n'?为什么使用'Array'构造函数而不是'var newArray = []'? – Mathletics

+0

不必。只需使用OP代码即可获得他想要的内容。我做了这些变化,谢谢@Mathletics – gfrobenius

0

someFunction需要类型的阵列1个输入,而不是4个输入:

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])); 
+0

真实。但是这样做会使功能毫无意义。你可以用'function someFunction(n){return n; ''并获得同样的结果。 OP想要这种格式:'someFunction(3,5,4,5)'。 – gfrobenius

2

可以做到这一点作为一个班轮:

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

这里的问题在C分解颂。

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; 
} 
+0

你会发现,有时候讽刺会诀窍。感谢您的详细解答! – Lucky500

0

直接构建数组的解决方案。

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

 
document.write('<pre>' + JSON.stringify(someFunction(3, 5, 4, 5), 0, 4) + '</pre>');