arguments的深入学习

123 阅读1分钟

arguments的深入学习

arguments是一个 传递给函数的参数 的类数组(array-like)对象.

arguments的基本使用

function foo(num1, num2, num3) {
  // 类数组: 长的像,本质是一个对象{}.
  console.log(arguments); // AO  [Arguments] { '0': 1, '1': 3, '2': 3, '3': 6, '4': 8 }
  // 对arguments的三种操作
  console.log(arguments.length);
  console.log(arguments[2]);
  // 获取arguments所在的函数
  console.log(arguments.callee);
  
  // arguments.callee() // 这样调用会出现递归
}

foo(1, 3, 3, 6, 8)

arguments转为数组(4种方式)

function foo(num1, num2, num3) {
  // console.log(arguments);

  // 1.自己遍历arguments的元素.

  // 2.使用数组的slice方法转为array
  // 通过Array.prototype调用slice(),绑定this为arguments(显式>隐式Array.prototype)
  // slice内部会拿到arguments进行遍历,并返回新数组
  var newArr1 = Array.prototype.slice.call(arguments) 
  console.log(newArr1);
  
  // 3.通过call显式绑定this为 arguments.返回新数组(具体实现如下)
  var newArr2 = [].slice.call(arguments)
  console.log(newArr2);

  // 4.ES6的语法
  // 4.1 Array.from() 传入可遍历的或者类数组(arguments)
  var newArr3 = Array.from(arguments)
  console.log(newArr3);
  // 4.2 展开运算符
  var newArr4 = [...arguments]
  console.log(newArr4);

}

foo(1, 3, 3, 6, 8)

Array中的slice()实现

Array.prototype.FhSlice = function(start, end) {
  // 拿到当前调用的数组
  var arr = this
  // 对参数进行处理
  start = start || 0
  end = end || arr.length
  // 对数组遍历并且返回
  var newArr = []
  for(var i = start; i < end; i++) {
    newArr.push(arr[i])
  }
  return newArr
}

var newArr = [1,2,3,4].FhSlice(1, 3)
console.log(newArr);

箭头函数没有arguments

// 测试箭头函数的arguments
function foo() {
  var bar = () => {
    console.log(arguments)
  }
  return bar
}

var fn = foo(123)
fn() // node: [Arguments] { '0': 123 }

// 不能用arguments,可以使用剩余参数
var foo = (num1, num2, ...args) => {
  console.log(args)
}

foo(10, 20, 30, 40, 50)