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。

3.类数组转化为数组的方法
Array.prototype.slice.call(arrayLike)

Array.prototype.slice的内部实现

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方法(它将传入的第二个参数(应该是一个数组)作为函数参数调用调用它的函数)来实现

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

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

转载于:https://my.oschina.net/u/3400107/blog/1840284

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值