javascript 類數組概念詳解

javascript 類數組概念詳解

1.什麼是類數組(ArrayLike)

  1. 自己是一個對象,擁有length屬性,其它屬性(索引)爲非負整數(對象中的索引會被當作字符串來處理,這裏你能夠當作是個非負整數串來理解)
  2. 不具備數組所具備的方法

2.判斷一個對象是否屬於類數組

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

3.類數組轉化爲數組的方法

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"]

4.將數組轉化爲類數組(以參數列表的形式)

能夠利用apply方法(它將傳入的第二個參數(應該是一個數組)做爲函數參數調用調用它的函數)來實現app

function convertToArrayLike(array){
    if(array instanceof Array){  
        return arguments.callee.apply(this,array)
    }
    else {
        return arguments;
    }
}

以上函數接受一個數組的輸入,輸出一個類數組函數

相關文章
相關標籤/搜索