Array.prototype.slice.call(arguments)的理解

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新增的数据结构SetMap)。

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");

更多精彩内容欢迎关注我的公众号!

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值