Array.prototype.slice.call()方法理解

相信很多同学翻看代码的时候都有看到类似下面这个方法

Array.prototype.slice.call()

逐个解析这个方法:

  • slice:用来截取截取字符串方法
  • Array: javascript的一个引用类型,其原型prototype上有一个方法叫slice
  • call和apply : 用来改变对象中函数内部的this引用

综上可以得知这个方法的主要目的是为了将类数组转化为数组

function test(a,b,c,d) 
{
    var arg = Array.prototype.slice.call(arguments,1); 
    alert(arg); 
} 
test("a","b","c","d"); //b,c,d

为什么不直接用 arguments.slice(1)呢 不是一样的么?

Array.prototype.slice.call(arguments, 1)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法。要是直接写arguments.slice(1)会报错。arguments 是object 不是Array ,他的原型上没有slice方法。

Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)

var a={length:2,0:'first',1:'second'};//类数组,有length属性,长度为2,第0个是first,第1个是second
console.log(Array.prototype.slice.call(a,0));// ["first", "second"],调用数组的slice(0);

var a={length:2,0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,1));//["second"],调用数组的slice(1);

var a={0:'first',1:'second'};//去掉length属性,返回一个空数组
console.log(Array.prototype.slice.call(a,0));//[]

function test(){
  console.log(Array.prototype.slice.call(arguments,0));//["a", "b", "c"],slice(0)
  console.log(Array.prototype.slice.call(arguments,1));//["b", "c"],slice(1)
}
test("a","b","c");

还有几个其他方法也可以达到类似功能:

1、Array.from

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

2、扩展运算符[...arg]

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://blog.youkuaiyun.com/astonishqft/article/details/82863315

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值