将数字推入数组

时间:2016-02-01 21:25:52

标签: javascript arrays

尝试做一些简单的事情,但不确定我做错了什么。

我只想调用带有数字参数的函数并将这些数字推送到一个新数组中......



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));
&#13;
&#13;
&#13;

这是bin

4 个答案:

答案 0 :(得分: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));

答案 1 :(得分:2)

你可以做一个单行:

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

此处列出了代码中的问题。

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

答案 2 :(得分: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]));

答案 3 :(得分:0)

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

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

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