zoukankan      html  css  js  c++  java
  • 类型检测 typeof和instanceof

    typeof

    typeof 用于返回以下原始类型

    • 基本类型:number/string/boolean
    • function
    • object
    • undefined

    可以使用typeof用于判断数据的类型

    let a = 1;
    console.log(typeof a); //number
    
    let b = "1";
    console.log(typeof b); //string
    
    //未赋值或不存在的变量返回undefined
    var hd;
    console.log(typeof hd);
    
    function run() {}
    console.log(typeof run); //function
    
    let c = [1, 2, 3];
    console.log(typeof c); //object
    
    let d = { name: "houdunren.com" };
    console.log(typeof d); //object

    instanceof

    instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

    也可以理解为是否为某个对象的实例,typeof不能区分数组,但instanceof则可以。

    let hd = [];
    let houdunren = {};
    console.log(hd instanceof Array); //true
    console.log(houdunren instanceof Array); //false
    
    let c = [1, 2, 3];
    console.log(c instanceof Array); //true
    
    let d = { name: "houdunren.com" };
    console.log(d instanceof Object); //true
    
    function User() {}
    let hd = new User();
    console.log(hd instanceof User); //true

    值类型与对象

    下面是使用字面量与对象方法创建字符串,返回的是不同类型。

    let hd = "houdunren";
    let cms = new String("hdcms"); 
    console.log(typeof hd, typeof cms); //string object
  • 相关阅读:
    C#
    if
    .net 5.0
    C# 未提供必须形参对应的实参
    EasyRTC报错 “[ERR] mod_local_stream.c:880 Unknown source default”排查
    EasyRTC通过公网进入会议室失败问题排查及解决
    【CF1558B】Up the Strip
    【AT Keyence2019E】Connecting Cities
    【洛谷P7470】岛屿探险
    【洛谷P6628】丁香之路
  • 原文地址:https://www.cnblogs.com/yyy1234/p/15827713.html
Copyright © 2011-2022 走看看