arrayObj.slice(start, [end]) 截取数组的一部分。
myFun.call([thisObj[,arg1[arg2[[argN]]]]]) thisObj调用myFun方法
Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组
function fun(x, y, z) {
//arguments并不是真正的数组对象 是一个带有length属性的对象 只是与数组类似而已 不是数组
//可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法
let args = Array.prototype.slice.call(arguments);
/*****真正原理******/
//Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组
//除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)
console.log(arguments, 'arguments');
console.log(args, 'args');
}
fun(1, 2, 3)
image.png
Array.prototype.slice.call方法测试
//类数组,有length属性,长度为2,第0个是first,第1个是second
var a={length:2,0:'first',1:'second'};
// ["first", "second"],调用数组的slice(0);
console.log(Array.prototype.slice.call(a,0));
var a={length:2,0:'first',1:'second'};
//["second"],调用数组的slice(1);
console.log(Array.prototype.slice.call(a,1));
//去掉length属性,返回一个空数组
var a={0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,0));//[]
function test(){
//["a", "b", "c"],slice(0)
console.log(Array.prototype.slice.call(arguments,0));
//["b", "c"],slice(1)
console.log(Array.prototype.slice.call(arguments,1));
}
test("a","b","c");
slice不传参数的结果测试
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var a = fruits.slice();
console.log(a);
//["Banana", "Orange", "Lemon", "Apple", "Mango"]
将函数的实际参数转换成数组的方法
//方法一:
var args = Array.prototype.slice.call(arguments);
//方法二:
var args = [].slice.call(arguments, 0);
//方法三:
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
通用:
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;
}
}
参考 https://blog.csdn.net/weixin_39337506/article/details/105232408