是否可以向JavaScript函数发送可变数量的参数?可以从数组向JavaScript函数发送可变数量的参数吗?var arr = ['a','b','c']var func = function(){
// debug
alert(arguments.length);
//
for(arg in arguments)
alert(arg);}func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'func(arr); // prints 1, then 'Array'我最近写了很多Python,能够接受varargs并发送它们是一个很好的模式。G.def func(*args):
print len(args)
for i in args:
print i
func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'func(*arr) // prints 4 which is what I want, then 'a','b','c','d'是否可以在JavaScript中发送待处理的数组如参数数组?
3 回答
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
var otherFunc = function() { alert(arguments.length); // Outputs: 10}var myFunc = function() { alert(arguments.length); // Outputs: 10 otherFunc.apply(this, arguments);}myFunc(1,2,3,4,5,6,7,8,9,10);
largeQ
TA贡献2039条经验 获得超7个赞
var arr = ['quick', 'brown', 'lazy'];var sprintf = function(str, ...args){ for (arg of args) { str = str.replace(/%s/, arg); } return str;}sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]); sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
sprintf('The %s %s fox jumps over the %s dog.', ...arr);
for...of
for...in
添加回答
举报
0/150
提交
取消