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;
    }
}

以上函数接受一个数组的输入,输出一个类数组函数

相关文章
相关标签/搜索