s基础进阶--关于Array.prototype.slice.call(arguments) 的思考

本文介绍了Array.prototype.slice.call(arguments)的作用,即强制将arguments转化为数组格式,解释了其等价形式及slice内部实现原理,还说明了call方法的作用。此外,还提到了利用ES6的Array.from()和展开表达式将arguments转化为数组的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Array.prototype.slice.call(arguments)的作用为:强制转化arguments为数组格式,一般出现在框架活插件的源码中

如何理解
上面的代码等价于[ ].slice.call(arguments)

或者随便一个数组调用都行 [1,2,4].slice.call(arguments)

因为,前面的调用者的作用只是沿着原型链向上找,最终找到Array为止,slice为Array原型上的一个方法

slice内部的实现原理大概是这样的

Array.prototype.slice = function(start,end){
var result = new Array();
start = start || 0; // 如果不传则取默认值
end = end || this.length; // 如果不传则取默认值

 //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键
 for(var i = start; i < end; i++){
      result.push(this[i]);
 }
 return result;

}
1
2
3
4
5
6
7
8
9
10
11
数组和字符串都有slice方法

如果对slice不是很了解,请看这篇文章:slice()与splice()的用法和区别你清楚吗?

call方法的作用为:改变调用者的this指向并且执行调用者,

function fn(a){
    console.log(this.a);
    console.log(this);
}

var obj = {
    a : 2
}

fn.call(obj); //  2 
              //  {a : 2} 
// 解释一下 fn的this指针指向了obj ,并且执行了fn函数

1
2
3
4
5
6
7
8
9
10
11
12
13
如果对call方法还是没理解,请看这边文章 js基础–深入理解call、apply、bind

arguments 为函数实参的一个集合,数据类型为对象类型

写一个例子吧
function ary(){
console.log(arguments,typeof arguments,arguments instanceof Object)

    // 自己实操一下  看看上面这行代码能打印出什么

    return [11,12].slice.call(arguments);

    //这里的[11,12]可以被替换为任意的数组,不影响结果
}

    var a11 = ary(1,2,3,4,5,6,888,9,222);

    console.log(a11);   [1, 2, 3, 4, 5, 6, 888, 9, 222]
    console.log(typeof a11);            //"object"
    console.log(a11 instanceof Array);  //ture

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
技术延伸
其实要实现将arguments强制转化为数组,还有几种方式

利用es6的Array.from()
function fn(){
var a = Array.from(arguments);
var b = Array.from(arguments).slice(1);
console.log(a);
console.log(b);
}

fn(1,2,6,3,4,12);
// 结果分别为 1,2,6,3,4,12  和 2,6,3,4,12

1
2
3
4
5
6
7
8
9
10
利用es6的展开表达式
function fn(){
var a = […arguments];
var b = […arguments].slice(1);
console.log(a);
console.log(b);
}

fn(1,2,6,3,4,12);
// 结果分别为 1,2,6,3,4,12  和 2,6,3,4,12

1
2
3
4
5
6
7
8
9
10

原文:https://blog.youkuaiyun.com/wxl1555/article/details/80329091

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值