Array.prototype.slice.call(arguments)

原理解释:

Array.prototype.slice.call()方法能够将一个具有length属性的对象转换为数组。比如我自己定义一个具有length属性的对象:

var obj = { 0: 'one', 1: 'two', 2: 'three', length: 3};
console.log(Array.prototype.slice.call(obj)); //  ["one", "two", "three"]
function foo(a,b,c,d) { 
   var arg = Array.prototype.slice.call(arguments); 
   console.log(arg); // ["a", "b", "c", "d"]
   console.log(typeof arguments); // object
   console.log(arguments); 
   //Arguments(4) ["a", "b", "c", "d", callee: ƒ, Symbol(Symbol.iterator): ƒ]
} 
foo("a","b","c","d"); 


Array.prototype.slice.call(arguments)的作用是将函数传入的参数转换为数组对象。那大家肯定有疑问,为什么不直接使用arguments对象呢?这里需要注意的是typeof arguments打印出的是object,可以看出arguments并不是真正的数组,它是一个对象。

ES6方法转为数组:

(1)、Array.from()

Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 es6新增的数据结构Set 和 Map)。

let demo = new Set(['a', 'b', 'c']);
Array.from(demo); // ['a', 'b', 'c'];

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

function foo(a,b,c,d) {
    console.log([...arguments]); // ["a", "b", "c", "d"]
}
foo("a","b","c","d");

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值