javascript 数据类型检测

数据类型检测

  • 基本数据类型一般用typeof

    typeof 'hello';		// string
    typeof('hello');	// string
    
  • 引用数据类型一般用instanceof

    let o = {
          
          };
    o instanceof Object;	// true
    
    let arr = [];
    arr instanceof Array;	// true
    
  • 使用Object.prototype.toString.call()判断数据类型

    // 基本数据类型
    Object.prototype.toString.call(null);		// [object Null]
    Object.prototype.toString.call(undefined);	// [object Undefined]
    Object.prototype.toString.call(1);			// [object Number]
    Object.prototype.toString.call(false);		// [object Boolean]
    Object.prototype.toString.call('string');	// [object String]
    Object.prototype.toString.call(Symbol('symbol'));	// [object Symbol]
    
    // 内部引用数据类型
    Object.prototype.toString.call([1,2,3]);	// [object Array]
    Object.prototype.toString.call(() => {
          
          });	// [object Function]
    Object.prototype.toString.call(new Date());	// [object Date]
    Object.prototype.toString.call(new RegExp());	// [object RegExp]
    
    // 自定义引用数据类型
    function Persion(_name='name', _age=18){
          
          
    	this.name = _name;
    	this.age = _age;
    }
    Object.prototype.toString.call(new Persion('girl'));	// [object Object]
    

猜你喜欢

转载自blog.csdn.net/SJ1551/article/details/109275091