zoukankan      html  css  js  c++  java
  • js中typeof与instanceof用法区别

    今天写JS代码,遇到动态生成多个名称相同的input复选按钮

    需要判断其是否是数组,用到了if (typeof(document.MapCheckMgr.checkid)!="undefined")

    以前用得少,就顺便查了一下关于typeof的那些事

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

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

    如:

    alert(typeof (123));//typeof(123)返回"number" 
    alert(typeof ("123"));//typeof("123")返回"string"

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

    正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时

    或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof

    instanceof用于判断一个变量是否某个对象的实例,如var a=new Array();alert(a instanceof Array);会返回true,

    同时alert(a instanceof Object)也会返回true;这是因为Array是object的子类。

    再如:function test(){};var a=new test();alert(a instanceof test)会返回true。

  • 相关阅读:
    php 类文件加载 Autoloader
    windows下配置nginx+php
    crontab 定时调度
    PHP 常见语法 集合
    php socket
    tengine + mysql + nginx + php
    yii2 [行为] behaviors 拦截器
    .htaccess 语法以及应用
    nginx 安装
    Nginx HTTP负载均衡和反向代理配置
  • 原文地址:https://www.cnblogs.com/zzsdream/p/6234616.html
Copyright © 2011-2022 走看看