javascript判断数据类型,判断是否是数组

数据类型判断

  • typeof 操作符返回一个字符串,指示未经计算的操作数的类型。
    <pre>
    var a = 'abc'; console.log(typeof a);//string
    var b = 1; console.log(typeof b); //number
    var c = false; console.log(typeof c); //boolean
    console.log(typeof undefined); //undefined
    console.log(typeof null); //object
    console.log(typeof {});// object
    console.log(typeof []);//object
    console.log(typeof (function(){}));//function
    </pre>

数组类型判断

  • instanceof,判断一个变量是否某个对象的实例
    <pre>
    var arr = [];
    arr instanceof Array;//true
    </pre>
  • constructor属性返回对创建此对象的函数的引用。
    <pre>
    var arr = [];
    arr.constructor === Array; //true
    </pre>
  • Object.prototype.toString(),为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,把需要检测的对象作为第一个参数传入。
    <pre>
    var arr = [];
    Object.prototype.toString.call(arr) === '[object Array]';//true
    //其他类型判断
    Object.prototype.toString.call(123) === '[object Number]';
    Object.prototype.toString.call('abc')) === '[object String]';
    Object.prototype.toString.call(undefined) === '[object Undefined]';
    Object.prototype.toString.call(true) === '[object Boolean]';
    Object.prototype.toString.call(function(){}) === '[object Function]';
    Object.prototype.toString.call(new RegExp()) === '[object RegExp]';
    Object.prototype.toString.call(null) === '[object Null]';
    </pre>
  • Array.isArray() 确定传递的值是否为Array。
    <pre>
    var arr = [];
    Array.isArray(arr);//true
    </pre>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容