Array.prototype.slice.call(arguments)的理解
- Array.prototype.slice.call(arguments)的理解
-
- 应用
- 原理
- 类似用法
- Array.from
- 扩展运算符(...)
Array.prototype.slice.call(arguments)的理解
应用
看一个简单的例子:
function foo(a,b,c,d) {
var arg = Array.prototype.slice.call(arguments);
console.log(arg);
console.log(typeof arguments);
console.log(arguments);
}
foo("a","b","c","d");
// ["a", "b", "c", "d"]
// object
Array.prototype.slice.call(arguments)
的作用是将函数传入的参数转换为数组对象。那大家肯定有疑问,为什么不直接使用
arguments
对象呢?这里需要注意的是
typeof arguments
打印出的是
object
,可以看出
arguments
并不是真正的数组,它是一个对象。
原理
Array.prototype.slice.call()
方法能够将一个具有
length
属性的对象转换为数组。比如我自己定义一个具有length属性的对象:
var a = { 0: 'bob', 1: '12', 2: 'male', length: 3};
console.log(Array.prototype.slice.call(a)); // ["bob", "12", "male"]
类似用法
将函数参数转换为数组除了
Array.prototype.slice.call(arguments)
方法外,还可以这么使用
[].slice.call(arguments)
,作用是等价的。
Array.from
上面的写法是
es5
中的写法,
es6
中提供了一个等价的方法实现上述功能
Array.from(arguments)
。
Array.from
方法用于将两类对象转为真正的数组:类似数组的对象
(array-like object)
和可遍历
(iterable)
的对象(包括
es6
新增的数据结构
Set
和
Map
)。
let bar = new Set(['a', 'b', 'c']);
Array.from(bar ); // ['a', 'b', 'c'];
扩展运算符(…)
es6
的语法中还提供了一个神器,叫做扩展运算符
(...)
,它也可以将某些数据结构转换为数组。比如:
function foo(a,b,c,d) {
// console.log(Array.prototype.slice.call(arguments));
// console.log(Array.from(arguments));
console.log([...arguments]); // ["a", "b", "c", "d"]
}
foo("a","b","c","d");
更多精彩内容欢迎关注我的公众号!
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBHL0FWby9mZvwVZnFWbp1zczV2YvJHctM3cv1Ce-EVT6FkeNRTWUplMVdkToJFVPd3YU1kdFpHT6hzQNlXQq1kd4cVY1VFSkBHauxUdSJTW0F1RiZHZXxUeWJzYxkTeMZTTINGMShUYvwlbj5yZtlmbkN3YuQnclZnbvN2Ztl2Lc9CX6MHc0RHaiojIsJye.jpg)