what is the best way to check variable type in javascript

后端 未结 6 800
天涯浪人
天涯浪人 2020-12-15 22:41


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 23:20

    use typeof();

    example:

    > typeof "foo"
    "string"
    > typeof true
    "boolean"
    > typeof 42
    "number"
    

    So you can do:

    if(typeof bar === 'string') {
       //whatever
    }
    

    Keep in mind that, typeof is only good for returning the "primitive" types, number, boolean, object, string. You can also use instanceof to test if an object is of a specific type.

    function MyObj(prop) {
      this.prop = prop;
    }
    
    var obj = new MyObj(10);
    
    console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
    

提交回复
热议问题