js 判断数据类型(string,number,Object,boolean,Array,function,undefined,Null,NaN,symbol)

判断类型

string,number,Object,boolean,Array,function,undefined,Null,NaN,symbol

方法

 function gettype(obj) {
    
    
   var type = typeof obj;
   // 如果要判断NaN
   if (String(obj) === "NaN" && type !== "string") {
    
    
     return "NaN";
   }
   if (type !== "object") {
    
    
     return type;
   }
   //如果不是object类型的数据,直接用typeof就能判断出来

   //如果是object类型数据,准确判断类型必须使用Object.prototype.toString.call(obj)的方式才能判断
   return Object.prototype.toString
     .call(obj)
     .replace(/^\[object (\S+)\]$/, "$1");
 }

例子

 let list = [
      "sdf",
      123,
      {
    
    },
      false,
      true,
      ["a", "a13"],
      () => {
    
    
        return 123;
      },
      function fn(a = 0) {
    
    
        return a;
      },
      undefined,
      null,
      NaN,
      Symbol()
    ];
 list.forEach((item, index) => {
    
    
      console.log(
        "index:",
        index,
        ";",
        "item:",
        item,
        ";",
        "item类型:",
        gettype(item),
        ";"
      );
    });
//  index: 0 ; item: sdf ; item类型: string ;
//  index: 1 ; item: 123 ; item类型: number ;
//  index: 2 ; item: {} ; item类型: Object ;
//  index: 3 ; item: false ; item类型: boolean ;
//  index: 4 ; item: true ; item类型: boolean ;
//  index: 5 ; item: (2) ["a", "a13"] ; item类型: Array ;
//  index: 6 ; item: ƒ () {
    
    
//       return 123;
//     } ; item类型: function ;
//  index: 7 ; item: ƒ fn() {
    
    
//       var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
//       return a;
//     } ; item类型: function ;
//  index: 8 ; item: undefined ; item类型: undefined ;
//  index: 9 ; item: null ; item类型: Null ;
//  index: 10 ; item: NaN ; item类型: NaN ;
//  index: 11 ; item: Symbol() ; item类型: symbol ;

猜你喜欢

转载自blog.csdn.net/weixin_43245095/article/details/118548036