zoukankan      html  css  js  c++  java
  • js判断是否为空和typeof的用法

    (1)typeof作用
    用于查看数据类型

    (2)typeof用法
    typeof 返回值类型有number, string, boolean, function, undefined, object
    PS:在使用typeof()操作符时圆括号是可选项,可带可不带。即两种形式 typeof(XX) 或 typeof XX

    1  console.log(typeof 2); // number
    2  console.log(typeof "2"); // string
    3  console.log(typeof true); // boolean
    4  console.log(typeof [2]); // object
    5  console.log(typeof {name:2});// object
    6  console.log(typeof function(){return 2});// function
    7  console.log(typeof new Date());// object
    8  console.log(typeof null); // object
    9  console.log(typeof undefined);// undefined

    但typeof只能区分number, string, boolean, function及undefined,其他的对象、数组、日期、null等都返回Object,存在缺陷。
    利用Object.prototype.toString.call可以很好的区分各种类型(注:无法区分自定义对象类型,自定义类型可以采用instanceof区分)

     1 console.log(Object.prototype.toString.call("zhangsan"));//[object String]
     2 console.log(Object.prototype.toString.call(12));//[object Number]
     3 console.log(Object.prototype.toString.call(true));//[object Boolean]
     4 console.log(Object.prototype.toString.call(undefined));//[object Undefined]
     5 console.log(Object.prototype.toString.call(null));//[object Null]
     6 console.log(Object.prototype.toString.call({name: "zhangsan"}));//[object Object]
     7 console.log(Object.prototype.toString.call(function(){}));//[object Function]
     8 console.log(Object.prototype.toString.call([]));//[object Array]
     9 console.log(Object.prototype.toString.call(new Date));//[object Date]
    10 console.log(Object.prototype.toString.call(/d/));//[object RegExp]
    11 function Person(){};
    12 console.log(Object.prototype.toString.call(new Person));//[object Object]

    (3)js判断是否为空

    1 var exp = null; 
    2 if (!exp && typeof(exp)!="undefined" && exp!=0 && exp!='') 
    3 { 
    4   alert("is not null"); 
    5 } 
  • 相关阅读:
    Django如何把数据库里的html格式输出到前端
    如何修改Django中的日期和时间格式 DateTimeField
    python2.7无法安装python-ldap、django-auth-ldap
    windows10下Python如何设置环境变量
    微信小程序在开发者工具页面显示空白且控制台看不到报错信息
    CentOS7 升级 openssh 到 openssh-8.0p1版本
    CentOS系统升级OpenSSH版本
    SSL相关漏洞解决方法
    CentOS 7.4安装 MySQL数据库
    Python3 基础知识
  • 原文地址:https://www.cnblogs.com/xmm2017/p/11470323.html
Copyright © 2011-2022 走看看