Javascript 是否可以将函数的所有参数作为该函数内的单个对象获取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4633125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:22:30  来源:igfitidea点击:

Is it possible to get all arguments of a function as single object inside that function?

javascriptalgorithmfunctionargumentsmarshalling

提问by rsk82

In PHP there is func_num_argsand func_get_args, is there something similar for JavaScript?

在 PHP 中有func_num_argsand func_get_args,JavaScript 有类似的东西吗?

回答by Thomas Eding

Use arguments. You can access it like an array. Use arguments.lengthfor the number of arguments.

使用arguments. 您可以像访问数组一样访问它。使用arguments.length的参数的数目。

回答by Luke

The argumentsis an array-like object(not an actual array). Example function...

所述参数类似阵列的对象(不是实际的阵列)。示例函数...

function testArguments () // <-- notice no arguments specified
{
    console.log(arguments); // outputs the arguments to the console
    var htmlOutput = "";
    for (var i=0; i < arguments.length; i++) {
        htmlOutput += '<li>' + arguments[i] + '</li>';
    }
    document.write('<ul>' + htmlOutput + '</ul>');
}

Try it out...

试试看...

testArguments("This", "is", "a", "test");  // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9);          // outputs [1,2,3,4,5,6,7,8,9]

The full details: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

完整细节:https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

回答by Gunnar Forsgren - Mobimation

ES6 allows a construct where a function argument is specified with a "..." notation such as

ES6 允许使用“...”符号指定函数参数的构造,例如

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}

回答by iConnor

The argumentsobject is where the functions arguments are stored.

arguments对象是函数的参数的存储位置。

The arguments object acts and looks like an array, it basically is, it just doesn't have the methods that arrays do, for example:

arguments 对象的行为和看起来像一个数组,它基本上是,它只是没有数组所做的方法,例如:

Array.forEach(callback[, thisArg]);

Array.forEach(callback[, thisArg]);

Array.map(callback[, thisArg])

Array.map(callback[, thisArg])

Array.filter(callback[, thisArg]);

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

Array.indexOf(searchElement[, fromIndex])

I think the best way to convert a argumentsobject to a realArray is like so:

我认为将arguments对象转换为真实数组的最佳方法是这样的:

argumentsArray = [].slice.apply(arguments);

That will make it an array;

这将使它成为一个数组;

reusable:

可重复使用的:

function ArgumentsToArray(args) {
    return [].slice.apply(args);
}

(function() {
   args = ArgumentsToArray(arguments);

   args.forEach(function(value) {
      console.log('value ===', value);
   });

})('name', 1, {}, 'two', 3)

result:

结果:

> value === name
> value === 1
> value === Object {}
> value === two
> value === 3

> value === name
> value === 1
> value === Object {}
> value === two
>value === 3

回答by Iman Mohamadi

You can also convert it to an array if you prefer. If Array generics are available:

如果您愿意,也可以将其转换为数组。如果 Array 泛型可用:

var args = Array.slice(arguments)

Otherwise:

除此以外:

var args = Array.prototype.slice.call(arguments);

from Mozilla MDN:

来自Mozilla MDN

You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example).

您不应该对参数进行切片,因为它会阻止 JavaScript 引擎(例如 V8)中的优化。

回答by Lasse Skindstad Ebert

As many other pointed out, argumentscontains all the arguments passed to a function.

正如许多其他人指出的那样,arguments包含传递给函数的所有参数。

If you want to call another function with the same args, use apply

如果要使用相同的参数调用另一个函数,请使用 apply

Example:

例子:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")

回答by Frank Nocke

Similar answer to Gunnar, with more complete example: You can even transparently return the whole thing:

与 Gunnar 类似的答案,有更完整的例子:你甚至可以透明地返回整个事情:

function dumpArguments(...args) {
  for (var i = 0; i < args.length; i++)
    console.log(args[i]);
  return args;
}

dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });

Output:

输出:

foo
bar
true
42
["yes","no"]
{"banana":true}

https://codepen.io/fnocke/pen/mmoxOr?editors=0010

https://codepen.io/fnocke/pen/mmoxOr?editors=0010

回答by Rubi saini

Yes if you have no idea that how many arguments are possible at the time of function declaration then you can declare the function with no parameters and can access all variables by arguments array which are passed at the time of function calling.

是的,如果您不知道在函数声明时可能有多少个参数,那么您可以声明没有参数的函数,并且可以通过在函数调用时传递的参数数组访问所有变量。

回答by Kamil Kie?czewski

In ES6 you can do something like this:

在 ES6 中,您可以执行以下操作:

function foo(...args) 
{
   let [a,b,...c] = args;

   console.log(a,b,c);
}


foo(1, null,"x",true, undefined);

回答by Paul Sweatte

In ES6, use Array.from:

在 ES6 中,使用Array.from

function foo()
  {
  foo.bar = Array.from(arguments);
  foo.baz = foo.bar.join();
  }

foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"

For non-ES6 code, use JSON.stringify and JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

对于非 ES6 代码,使用 JSON.stringify 和 JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

如果需要保存而不是字符串化,请使用内部结构化克隆算法

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

如果 DOM 节点被传递,请使用 XMLSerializer 作为一个无关的问题

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringifyto work properly.

如果作为书签运行,您可能需要将每个结构化数据参数包装在 Error 构造函数中JSON.stringify才能正常工作。

References

参考