关于Array.prototype.slice.call(arguments)

101 阅读1分钟

首先啊我们来看个例子:

function foo(a,b,c,d){
    let arg = Array.prototype.slice.call(arguments)
     console.log(arg)
     console.log(typeof arguments)
     console.log(arguments)
     console.log(arguments.length)
}

foo(1,2,3,4)
console.log(arg)  // [1,2,3,4]
console.log(typeof arguments) //Object
console.log(arguments) // [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
console.log(arguments.length) // 4

通过结果我们看到得到的arg是一个数组,而argument是一个对象,我们称具有length属性,其他属性(索引)为非负整数的数组对象称为类数组,他不具备数组的方法。在这中间Array.prototype.slice.call(arguments)将数组slice方法通过call绑定this指向arguments,使arguments具有数组方法(回忆时间:slice(start,end)方法并不会修改数组,而是返回一个子数组,不传参时会返回全部)

至此我们可以知道Array.prototype.slice.call()方法能够将一个具有length属性的对象转换为数组

区别数组与类数组的方法:

(1) arr instanceof Array

(2) arr.constructor === Array

(3) Array.isArray(arr)

(4) Object.prototype.toString.call(arr) === '[Object Array]'

类似方法

1、new Set() + Array.from()

let foo = new Set(arguments)
foo = Array.from(foo)

2.扩展运算符(...)

console.log([...arguments]) // [1,2,3,4]