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; } }
以上函數接受一個數組的輸入,輸出一個類數組函數