美文网首页
typeof 和 instanceof

typeof 和 instanceof

作者: Ace__丨 | 来源:发表于2019-06-22 10:40 被阅读0次
    typeof可能会返回如下的值:

    1."undefined",
    2."boolean",
    3."string",
    4."number",
    5."object",
    6."function"

    let u;
    console.log(typeof(u)); //"undefined"
    
    let n = null;
    console.log(typeof(n)); //"object"    null表示一个空对象指针,所以使用typeof返回"object"
    
    let b = true;
    console.log(typeof(b)); //"boolean"
    
    let s = "hello";
    console.log(typeof(s)); //"string"
    
    let n = 123;
    console.log(typeof(s)); //"number"
    
    let nan = NAN;
    console.log(typeof(nan)); //"number"
    
    let obj = new Object();
    console.log(typeof(obj)); //"object"
    
    let arr = [];
    console.log(typeof(arr)); //"object"
    
    let f = function(){};
    console.log(typeof f); //"function"
    
    typeof是检测一个变量是不是基本数据类型的最佳工具,但在检测引用类型值的时候,我们会使用instanceof

    所有引用类型的值都是Object的实例,在检测引用类型和Object构造函数时,instanceof都会返回true,当检测基本类型时,都会返回false

    function Person() {};
    let person = new Person();
    console.log(person instanceof Object);//true
    console.log(person instanceof Person);//true
    
    let arr = [];
    console.log(arr instanceof Array);//true
    

    总结:确定一个值是那种基本类型可以使用typeof,而确定一个值是哪种引用类型可以使用instanceof

    相关文章

      网友评论

          本文标题:typeof 和 instanceof

          本文链接:https://www.haomeiwen.com/subject/xazjqctx.html