类数组转换为数组实现
基础知识:
- Array 是数组类;
- slice(start,end)是此类中的方法;
- 类中调用slice()方法,应该是Array.prototype.slice(start,end);
call([thisObj[,arg1[arg2[[argN]]]]])
params:
thisObj是一个对象的方法
arrg1~argN是参数
实现原理: Array.prototype.slice.call(argument);能将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");
将参数转换为数组的方式:
- Array.from(arrayLike);
- Array.prototype.slice.call(arguments);
- [].slice.call(arguments,0);
- function ArrayTransfer(...args){ var args=[]; for(var i=0;i<arguments.length;i++){ args.push(arguments[i]); } }