Javascript 将函数入参arguments转化为数组
阅读(3292)
function hello() {
arguments.unshift('hello');
alert(arguments.join(' '));
}
hello('pretty', 'world');
直接执行,会报错:
TypeError: undefined is not a function
原因在于入参并不是一个真正的数组:
The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length.
via: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
可以利用数组的原型继承方式,来转化成一个真正的数组:
var args = Array.prototype.slice.call(arguments);