数组 / 伪数组 判断及方法调用 (权威指南笔记)

判断是不是数组

var isArray = Function.isArray || function(o) {
    return typeof o === "object" &&
    Object.prototype.toString.call(o) === "[object Array]";
};

判断是不是伪数组

function isArrayLike(o){
    if(o &&                                       //o非null.undefined
        typeof o === "object" &&                  //o是对象
        isFinite(o.length) &&                     //o.length是有限数值
        o.length > 0 &&                           //o.length为非负数
        o.length === Math.floor(o.length) &&      //o.length是整数
        o.length < 4294967296 ){                  //o.length<2^32         
        return true;
    }else{
        return false;
    }
}

伪数组   数组方法兼容性写法

Array.join = Array.join || function(a,sep){
    return Array.prototype.join.call(a,sep);
}
Array.slice = Array.slice || function(a,from,to){
    return Array.prototype.slice.call(a,from,to);
}
Array.map = Array.map || function(a,f,thisArg){
    return Array.prototype.map.call(a,f,thisArg);
}

用数组的方法操作字符串

var s = javascript;
s.charAt(0);                          //原生的方法  >='j'
s[0]                                  //>='j'

Array.prototype.join.call(s," ")      //=> "j a v a s c r i p t"
Array.prototype.filter.call(s,function(x){
    return x.match(/[^aeiou]/);
}).join("");                          //=> "jvscrpt"  

/*需注意,字符串是不变值,故当把它们作为数组看待时,它们是只读的,
数组的,push、sort、reverse、splice 等方法对它无效,而且使用这些
方法出现错误时,也不会有错误提示!!!*/
原文地址:https://www.cnblogs.com/ysxq/p/6780051.html