将参数转换为数组

The arguments object thats automatically available within functions can be a source of confusion for some people; it's kind of an array but it's kinda not. JavaScript is awesome in that you can pass any number of arguments to a function, and oftentimes developers need to iterate over every argument provided.  The arguments object doesn't have a forEach method, but using a quick JavaScript technique, you can convert arguments to an array:

arguments自动可用的arguments对象可能会使某些人感到困惑。 它有点像数组,但不是。 JavaScript很棒,因为您可以将任意数量的arguments传递给函数,并且开发人员通常需要遍历所提供的每个参数。 arguments对象没有forEach方法,但是使用快速JavaScript技术,您可以将arguments转换为数组:


function myFn(/* any number of arguments */) {
	var args = Array.prototype.slice.call(arguments);
		// or [].slice.call(arguments)

	args.forEach(function(arg) {
		// do something with args here
	});
}


Much like converting a NodeList to an array, Array's slice method takes the arguments object and converts it to a true array, allowing for forEach, map, and traditional array iteration.  Keep that trick up your sleeve for future development.

就像将NodeList转换为数组一样 ,Array的slice方法采用arguments对象并将其转换为真实数组,从而允许forEach,map和传统数组迭代。 继续为将来的发展而忙。

翻译自: https://davidwalsh.name/arguments-array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值