简体   繁体   English

JavaScript 函数中的无限参数

[英]Unlimited arguments in a JavaScript function

Can a JavaScript function take unlimited arguments? JavaScript 函数可以接受无限参数吗? Something like this:像这样的东西:

testArray(1, 2, 3, 4, 5...);

I am trying:我在尝试:

var arr = [];
function testArray(A) {
    arr.push(A);
}

But this doesn't work (output is only the first argument).但这不起作用(输出只是第一个参数)。 Or the only way is:或者唯一的方法是:

function testArray(a, b, c, d, e...) {

}

Thanks谢谢

There's a weird "magic" variable you can reference called "arguments":您可以引用一个奇怪的“魔法”变量,称为“参数”:

function manyArgs() {
  for (var i = 0; i < arguments.length; ++i)
    alert(arguments[i]);
}

It's like an array, but it's not an array.就像一个数组,但它不是一个数组。 In fact it's so weird that you really shouldn't use it much at all.事实上,它太奇怪了,你根本不应该使用它。 A common practice is to get the values of it into a real array:一种常见的做法是将它的值放入一个真正的数组中:

function foo() {
  var args = Array.prototype.slice.call(arguments, 0);
  // ...

In that example, "args" would be a normal array, without any of the weirdness.在那个例子中,“args”将是一个普通的数组,没有任何奇怪的地方。 There are all sorts of nasty problems with "arguments", and in ECMAScript 5 its functionality will be curtailed. “参数”存在各种令人讨厌的问题,在 ECMAScript 5 中,它的功能将被缩减。

edit — though using the .slice() function sure is convenient, it turns out that passing the arguments object out of a function causes headaches for optimization, so much so that functions that do it may not get optimized at all.编辑——虽然使用.slice()函数确实很方便,但事实证明,将arguments对象传递出函数会导致优化的麻烦,以至于执行它的函数可能根本不会得到优化。 The simple, straightforward way to turn arguments into an array is therefore因此,将arguments转换为数组的简单直接的方法是

function foo() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  // ...
}

More about arguments and optimization. 更多关于arguments和优化。

As of ECMAScript 2015 (or ES6) we also have access to rest parameters that give us a slightly cleaner way to manage arguments:从 ECMAScript 2015(或 ES6)开始,我们还可以访问其余参数,这为我们提供了一种更简洁的方法来管理参数:

function foo(a, b, ...others) {
    console.log("a and b are ", a, b);

    for (let val of others) {
        console.log(val);
    }
}

foo(1, 2, 3, 4, 5);

At the time of this writing, this is supported by Chrome 47+, Firefox 15+, and Edge.在撰写本文时,Chrome 47+、Firefox 15+ 和 Edge 支持此功能。 The feature is also available via both Babel and TypeScript transpiling down to ES5.该功能也可通过BabelTypeScript转换为 ES5 使用。

With ECMAScript 6, you can use rest of arguments syntax:使用 ECMAScript 6,您可以使用其余参数语法:

const testArray = (...args) => {
    console.log(args);
};

testArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

You can also just "cast" it, saving you the ugly loop:您也可以“投射”它,从而节省丑陋的循环:

var getArguments = function() {
    return arguments;
};

var foo = getArguments(1,2,3,4);

// console.log(foo.slice()); => TypeError: foo.slice is not a function

var foo = Object.values(foo); 

console.log(foo); // => [ 1, 2, 3, 4 ]

foo.push(5);

console.log(foo); // => [ 1, 2, 3, 4, 5 ]

There are some legacy methods but I prefer the ES6 and newer versions, So if I wanna implement this, I wrote it like below:有一些遗留方法,但我更喜欢ES6和更新版本,所以如果我想实现这个,我写如下:

const func = ...arg => console.log(arg);

Simple and cutting edge of tech.简单而前沿的技术。

Javascript ES5 Javascript ES5

function testArray(){
    for(index = 0; index < arguments.length; i++) {
        alert(arguments[index])
    }
}

Javascript ES6 Javascript ES6

const testArray = (...arg) => console.log(arg)
function toArray() {
   return arguments;
}

var myargs = toArray(1, 2, 3, 4, 5, 6);

The arguments keyword is available in every js function arguments关键字在每个 js 函数中都可用

var arr = [];
function testArray() {
    Array.prototype.push.apply(arr, arguments);
}

 const outputDiv=document.querySelector('.output'); const output=(...x)=>{ return outputDiv.innerHTML=x; } output(1,2,3,4,['hello',5,6],true,null);
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Javascript Practice</title> <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,800;1,900&display=swap" rel="stylesheet"> <style> body{font-family: 'Raleway', sans-serif; background-color: #060606;} .center{height:100vh; width: 100%; display: grid;align-items:center;justify-content: center;} .output{font-size: 15px;color: rgb(59, 59, 255);font-weight: 200;} </style> </head> <body> <div class="center"> <div class='output'></div> </div> <script src="js.js"></script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM