Which is a better way to know the type of a variable in Java Script

This question already has an answer here:

  • Check if object is array? 38 answers
  • Difference between instanceof and constructor property 1 answer

  • 查看Array.isArray()函数:

    Array.isArray(a);
    

    if(typeof a === 'object' && Array.isArray(a)) {
        //its array
    }
    

    UPDATE : the difference

    var a = Object.create(Array.prototype);
    
    alert(a instanceof Array);                       //TRUE
    alert(a.constructor === Array);                  //TRUE  
    if (typeof a === 'object' && Array.isArray(a)) { //FALSE 
        alert(true);
    } 
    else {
        alert(false);
    }
    

    but then you do

    var a = new Array();  // or var a = [];  etc
    
    alert(a instanceof Array);                       //TRUE
    alert(a.constructor === Array);                  //TRUE  
    if (typeof a === 'object' && Array.isArray(a)) { //TRUE 
        alert(true);
    } 
    else {
        alert(false);
    }
    

    在下面返回一个用户的变量类型

    typeof(a)
    
    链接地址: http://www.djcxy.com/p/27584.html

    上一篇: 这是一个正确的条件?

    下一篇: 哪种方法可以更好地了解Java脚本中的变量类型