- 开门见山:slice()方法可从已有的数组中返回选定的元素。也就是截取数组的一部份
arrayObject.slice(start,end)
- call:
语法:call(thisObj, arg1, arg2, …)
定义:调用一个对象的一个方法,以另一个对象替换当前对象。 - Array.prototype.slice.call(arguments,1);这句话的意思就是说把调用方法的参数截取出来。
function sum() {
console.log(arguments);
let arg = Array.prototype.slice.call(arguments,0);
let arg1 = [].slice.call(arguments,0);
// 这里的[] == Array.prototype;
// 这里的slice.call()的方法,是截取数组
console.log(arg) //[1, 2, 3, 4, 5, 6]
console.log(arg1) // [1, 2, 3, 4, 5, 6]
}
sum(1,2,3,4,5,6);
我们先看上面的这个例子:
let arg = Array.prototype.slice.call(arguments,0); 等同于下面的
let arg = arguments.slice.call(0);
但是为什么要用上面的写法,两者又有什么区别呢?
这个是使用let arg = arguments.slice.call(0);出来的结果:
;的时候,可以将arguments转换成一个数组对象,这样的话,arguments就具有slice()
最后我们来看一下这个原理:
Array.prototype.slice.call(arguments,0)能将具有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.prototype.slice.call(arguments);
(2) [].slice.call(arguments, 0);
(3) var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
(4)万能转化函数:
var toArray = function(s){
try{
return Array.prototype.slice.call(s);
} catch(e){
var arr = [];
for(var i = 0,len = s.length; i < len; i++){
//arr.push(s[i]);
arr[i] = s[i]; //据说这样比push快
}
return arr;
}
}
补充:上面的是这种对arguments的一种处理方式,如果使用的是es的话,完全可以使用扩展运算符(…arg)这种方法,这个可以直接将传入的形参转化成数组的形式。