首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Array对象的判定

Array对象的判定

作者头像
郑小超.
发布2018-01-24 16:21:45
6750
发布2018-01-24 16:21:45
举报
文章被收录于专栏:GreenLeavesGreenLeaves
  /*
    关于JS对象类型的判断,最复杂的在于RegExp和Array了,判定RegExp的情形不较少,而Array就比较多了,下面就是判断Array的方法
     */

    //方法一:利用instanceof来判断对象是不是Array的实例
    function isArray(arr){
        return arr instanceof Array;
    }

    //方法二:利用constructor来判断
    function isArray(arr)
    {
        return !!arr && arr.constructor==Array;
    }

    //方法三:利用constructor和array的内置属性(实例方法)来判断一个对象是否是Array类型
    function isArray(arr) {
        return arr && typeof arr==="object" &&  'splice' in arr && 'join' in arr;
    }

    //方法四:通过sort方法的类型判断arr是不是Array对象的实例
    function isArray(arr)
    {
        return typeof arr.sort==="function";
    }

    //方法五:通过Array.prototype.toString.call()方法来判断对象
    function isArray(o) {
        try
        {
            Array.prototype.toString.call(o);
            return true;
        }
        catch (e)
        {}
        return false;
    }

    //方法六:通过typeof和数组的length属性来判断
    function isArray(o) {
        if(o && typeof o=="object" && typeof o.length=="number" && isFinite(o.length))
        {
            //通过length属性是否符合原生数组的length的特性来进行双重判定
            var _originalLength=o.length;
            o[o.length]="_test_";
            var _newLength=o.length;
            o.length=_originalLength;
            return _newLength==o.length+1;
        }
        return false;
    }

    //方法七:
    function isArray(array) {
        var result=false;
        try
        {
            new array.constructor(Math.pow(2,32));
        }
        catch(e)
        {
            result=/Array/.test(e.message);
        }
        return result;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-02-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档