function isArrayLike(o) { if (o && // o is not null, undefined, etc. typeof o === 'object' && // o is an object isFinite(o.length) && // o.length is a finite number o.length >= 0 && // o.length is non-negative o.length===Math.floor(o.length) && // o.length is an integer o.length < 4294967296) // o.length < 2^32 return true; // Then o is array-like else return false; // Otherwise it is not }
isFinite():若是参数是 NaN(调用isNaN()返回true),正无穷大或者负无穷大,会返回false,其余返回 true。javascript
Array.prototype.slice.call(arrayLike)
Array.prototype.slice的内部实现java
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; }
根据slice的内部实现,若是类数组索引不以0开头会出现转化不全的状况,好比数组
var a = {1:'asda',2:'aa',length:2}; console.log(Array.prototype.slice.call(a));//[empty, "asda"]
能够利用apply方法(它将传入的第二个参数(应该是一个数组)做为函数参数调用调用它的函数)来实现app
function convertToArrayLike(array){ if(array instanceof Array){ return arguments.callee.apply(this,array) } else { return arguments; } }
以上函数接受一个数组的输入,输出一个类数组函数