zoukankan      html  css  js  c++  java
  • JavaScript测试数据类型的三种方法

    typeof


    console.log(typeof a);    //undefined
    
    console.log(typeof(true));  //boolean
    
    console.log(typeof '111');  //string
    
    console.log(typeof 111);   //number
    
    console.log(typeof NaN);   //number
    
    console.log(typeof null);  //object
    
    
    var str = new String();
    
    console.log(typeof(str));    //object
    
     
    var  fn = function(){};
    
    console.log(typeof(fn));  //function
    
     
    class Box{
    
      constructor(){
    
      }
    
    }
    
    var box = new Box();
    
    console.log(typeof box);  //object
    

    Object.prototype.toString.call();


    console.log(Object.prototype.toString.call("aaa"));  //[object String]
     
    console.log(Object.prototype.toString.call(111));  //[object Number]
     
    console.log(Object.prototype.toString.call(true));  //[object Boolean]
     
    console.log(Object.prototype.toString.call(undefined));  //[object Undefined]
     
    console.log(Object.prototype.toString.call(null));  //[object Null]
     
    console.log(Object.prototype.toString.call({name: "zhang"}));  //[object Object]
     
    console.log(Object.prototype.toString.call(function(){}));  //[object Function]
     
    console.log(Object.prototype.toString.call([]));  //[object Array]
     
    console.log(Object.prototype.toString.call(new Date));  //[object Date]
     
    console.log(Object.prototype.toString.call(/a/));  //[object RegExp]
    
    class Test{
      constructor(){
    
      }
    }
    var test = new Test();
    console.log(Object.prototype.toString.call(test));  //[object Object]
    

    constructor


    console.log((111).constructor.name)   //Number
    
    console.log(("111").constructor.name)    //String
    
    console.log((aaa).constructor.name)   //aaa is not defined
    
    console.log((/a/).constructor.name)   //RegExp
    
    console.log((true).constructor.name)   //Boolean
    
    console.log(({name:"zhang"}).constructor.name)   //Object
    
    console.log((new Date).constructor.name)   //Date
    
    console.log(([]).constructor.name)   //Array
    
    console.log((function(){}).constructor.name)   //Function
    
    class Box{
      constructor(){
    
      }
    }
    var test = new Box();
    console.log(test.constructor.name)   //Box
    
  • 相关阅读:
    换手机了,dopod566,小E丢了 :(
    在a标签的href与onclick中使用javascript的区别
    我的SQL相关TIPS
    asp.net的ajax服务器端代理
    IE和Firefox中的dom加载完成执行代码(defer)
    看几个源码,自己多做项目了!
    数据层使用Server对象;动态生成控件多文件上传
    ref,out(摘)
    JavaScript和jQuery的DOM操作
    闭包
  • 原文地址:https://www.cnblogs.com/JHJavaScript/p/11420770.html
Copyright © 2011-2022 走看看