zoukankan      html  css  js  c++  java
  • 小tips:JS中typeof与instanceof用法

    介绍

    typeof

    typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:

    • number
    • boolean
    • string
    • function(函数)
    • object(NULL,数组,对象)
    • undefined。

    例子:

    function curFun(){};
    var numberType = 123;
    var stringType = "123";
    var booleanType = false;
    var obj = {};
    var nullType = null;
    var arrayType = [];
    var unden;
    
    console.log(typeof curFun); //function
    
    console.log(typeof numberType);//number
    console.log(typeof stringType);//string
    console.log(typeof booleanType); //boolean
    
    console.log(typeof obj); //object
    console.log(typeof nullType); //object
    console.log(typeof arrayType); //object
    
    console.log(typeof unden); //undefined

    我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,

    正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof

    instanceof

    instanceof用于判断一个变量是否某个对象的实例

    var arr = new Array();
    console.log(arr instanceof Array); //true
    console.log(arr instanceof Object) //true,因为Array是object的子类
    function test(){};
    var testInstance = new test();
    console.log(testInstance instanceof test); //true

    js判断变量是否未定义的代码

    一般如果变量通过var声明,但是并未初始化的时候,变量的值为undefined,而未定义的变量则需要通过 "typeof 变量"的形式来判断,否则会发生错误。
    实际应用:
    variable有的页面我们不定义,但有的页面定义了,就可以需要这样的判断方法,没有定义的就不执行。

    if("undefined" != typeof variable){ 
        if(variable=="abc"){ 
            console.log('成功'); 
        } 
    }
  • 相关阅读:
    Hadoop学习之编译eclipse插件
    js堆栈溢出错误
    java——推断日期是否在今天之前
    AlertDialog.Builder中的setMultiChoiceItems中的事件处理
    Qemu之Network Device全虚拟方案二:虚拟网卡的创建
    【Android Tricks 6】ViewPager首页与尾页的滑动动作响应
    JFinal开发web项目出现故障小记
    HDU-4407-Sum(容斥原理)
    自己动手写CPU之第五阶段(3)——MIPS指令集中的逻辑、移位与空指令
    待字闺中之巧妙排序分析:
  • 原文地址:https://www.cnblogs.com/moqiutao/p/7510846.html
Copyright © 2011-2022 走看看