arguments

176 阅读1分钟

arguments的对象是什么

  • arguments 对象是函数中传递的参数值的集合。它是一个类似数组的对象,因为它有一个length。
  • 可以使用数组索引表示法argument[1]来访问单个值,但它没有数组中的内置方法,如:forEach、redece、filter和map  
  • 可以使用Array.prototype.slice将arguments对象转换成一个数组。
 function one(){
    return Array.prototype.slice.call(arguments);
 }
  • 箭头函数没有arguments对象
 funtion one(){
     return arguments;
 }
 const two = function(){
     return arguments;
 }
 const three = function(){
     return arguments;
 }

 const four = () => arguments;

 four();//Throws an error - arguments is not defined
  • 当使用four会报错。解决方式使用rest语法。
 const four = (...args) => args;
  • 这会自动将所有参数放入数组