【发布时间】:2011-06-05 17:02:25
【问题描述】:
在 PHP 中有 func_num_args 和 func_get_args,JavaScript 有类似的吗?
【问题讨论】:
标签: javascript algorithm function arguments marshalling
在 PHP 中有 func_num_args 和 func_get_args,JavaScript 有类似的吗?
【问题讨论】:
标签: javascript algorithm function arguments marshalling
使用arguments。您可以像访问数组一样访问它。使用arguments.length 作为参数数量。
【讨论】:
function,不适用于 ES2015+ 胖箭头 => 函数。对于那些,你会想在函数定义中使用...args,如下所示:(...args) => console.log(args)。
参数是an array-like object(不是实际的数组)。示例函数...
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>');
}
试试看……
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]
完整详情:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
【讨论】:
在 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"
对于非 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]
如果需要保存而不是字符串化,请使用internal structured cloning algorithm。
如果传递了 DOM 节点,则使用 XMLSerializer,就像在 unrelated question 中一样。
with (new XMLSerializer()) {serializeToString(document.documentElement) }
如果作为书签运行,您可能需要将每个结构化数据参数包装在 Error 构造函数中,以使 JSON.stringify 正常工作。
参考文献
【讨论】:
arguments 对象是存储函数参数的位置。
arguments 对象的行为和看起来像一个数组,它基本上是,它只是没有数组所做的方法,例如:
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
Array.indexOf(searchElement[, fromIndex])
我认为将 arguments 对象转换为 real 数组的最佳方法是这样的:
argumentsArray = [].slice.apply(arguments);
这将使它成为一个数组;
可重复使用:
function ArgumentsToArray(args) {
return [].slice.apply(args);
}
(function() {
args = ArgumentsToArray(arguments);
args.forEach(function(value) {
console.log('value ===', value);
});
})('name', 1, {}, 'two', 3)
结果:
>
value === name
>value === 1
>value === Object {}
>value === two
>value === 3
【讨论】:
[].slice.apply(arguments); 不是最好的方法,因为它会导致不必要的空数组分配。
如果您愿意,也可以将其转换为数组。如果数组泛型可用:
var args = Array.slice(arguments)
否则:
var args = Array.prototype.slice.call(arguments);
来自Mozilla MDN:
你不应该对参数进行切片,因为它会阻止优化 JavaScript 引擎(例如 V8)。
【讨论】:
function foo() { foo.bar = JSON.stringify(arguments); foo.baz = JSON.parse(foo.bar); } 如果需要保存而不是字符串化,请使用 internal structured cloning algorithm。如果传递了 DOM 节点,则使用 XMLSerializer,就像在 unrelated question 中一样。 with (new XMLSerializer()) {serializeToString(document.documentElement) }
正如许多其他人指出的那样,arguments 包含传递给函数的所有参数。
如果你想调用另一个具有相同参数的函数,请使用apply
例子:
var is_debug = true;
var debug = function() {
if (is_debug) {
console.log.apply(console, arguments);
}
}
debug("message", "another argument")
【讨论】:
是的,如果您不知道在函数声明时可能有多少个参数,那么您可以在没有参数的情况下声明该函数,并且可以通过在函数调用时传递的参数数组访问所有变量。
【讨论】:
ES6 允许使用“...”符号指定函数参数的构造,例如
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
【讨论】:
a = () => {console.log(arguments);}; a('foo'); 给-- Uncaught ReferenceError: arguments is not defined 但是a = (...args) => {console.log(args);}; a('foo'); 给["foo"]
与 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 });
输出:
foo
bar
true
42
["yes","no"]
{"banana":true}
【讨论】:
在 ES6 中你可以这样做:
function foo(...args)
{
let [a,b,...c] = args;
console.log(a,b,c);
}
foo(1, null,"x",true, undefined);
【讨论】:
希望这会有所帮助:
function x(...args) {
console.log( {...[...args] } );
}
x({a:1,b:2}, 'test');
输出:
{ '0': { a: 1, b: 2 }, '1': 'test' }
【讨论】: