将数字推入数组
回答
这将让这些数字进入你的阵列。并且它将做它提供无限数量: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,那就是我一直在寻找的。 – Lucky500
如果你不使用它,为什么要命名为arg'n'?为什么使用'Array'构造函数而不是'var newArray = []'? – Mathletics
不必。只需使用OP代码即可获得他想要的内容。我做了这些变化,谢谢@Mathletics – gfrobenius
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]));
真实。但是这样做会使功能毫无意义。你可以用'function someFunction(n){return n; ''并获得同样的结果。 OP想要这种格式:'someFunction(3,5,4,5)'。 – gfrobenius
可以做到这一点作为一个班轮:
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;
}
你会发现,有时候讽刺会诀窍。感谢您的详细解答! – Lucky500
直接构建数组的解决方案。
function someFunction() {
return Array.apply(null, arguments);
}
document.write('<pre>' + JSON.stringify(someFunction(3, 5, 4, 5), 0, 4) + '</pre>');
- 1. 将数组推入数组
- 2. 将数字列表推入数组中?
- 3. mongojs:将元素推入数组字段
- 4. php - 将数组推入数组 - (推按键和数组)
- 5. 将数组推入另一个数组?
- 6. 将关联数组推入数组
- 7. 将数组推入另一个数组
- 8. 将多维数组推入数组中?
- 9. PHP - 将数组推入数组?
- 10. PHP:将数组推入数组
- 11. 将对象推入数组
- 12. 将数组推入kb.collectionObservable
- 13. 将对象推入数组
- 14. 将值推入数组
- 15. 将哈希推入数组
- 16. 将对象推入数组
- 17. knockoutjs将嵌套数据推入数组
- 18. 将整数推入数组的问题
- 19. JavaScript,将数组推入函数
- 20. Angular:将数据推入嵌套数组
- 21. 将mysql数据推入数组
- 22. 将数据推入json数组
- 23. 将JSON数据推入数组?
- 24. 将php数组传入javascript,检查数组值并将其推入新数组
- 25. 如何将斐波那契数字推入外部数组?
- 26. 将(推?)字符串数据放入数组(或对象) - jQuery
- 27. PHP推入数组
- 28. 无法将对象推入数组,javascript
- 29. 将多个数组对象推入localhost?
- 30. 将火力点值推入数组
http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function看看这个 - 在这里解释如何应对可变数量的参数,如果我理解的话,就是你的主要问题。而且在这个http://www.w3schools.com/jsref/jsref_push.asp - 这里是如何将元素推送到一个javascript数组。 –
以MDN开头;你几乎在每一行都有问题。 – Mathletics