首页 » 乱七八糟 » js中的arguments对象

js中的arguments对象

js中的arguments对象

一直以来都简单认为function中的arguments是一个数组,但是却看到了Array.prototype.slice.call(arguments, 1) 这样诡异的写法。

  1. arguments并非真正的数组实例,不具备数组的slice、push、pop等方法。
(function () {
    console.log(arguments.toString()); //[object Arguments]
    console.log(arguments instanceof Array); // false
    console.log(arguments);// {0: 'Hello', 1: 'world', length: 2, callee: function()}
})('Hello', 'world');
  1. arguments是一个类数组对象,以0开始的数字为键,拥有表示长度的属性length,具有和Array相似的结构。所以可以借用Array.prototype的方法,使用call或apply来改变slice的调用对象为arguments,以达到arguments.slice(1)的目的。类似的pop、push等也可以使用这种方法调用。