js数据类型和判断数据类型的方法

时间: 2023-12-21 admin 维修知识

js数据类型和判断数据类型的方法

js数据类型和判断数据类型的方法

js数据类型

1.基本数据类型(原始类型):

  • number
  • boolean
  • string
  • null:空对象
  • undefined:未定义
  • Symbol(es6新增):
    • 表示独一无二的值。
    • 为了解决对象实例新的方法与已有方法名冲突问题 。
    • 每个从 Symbol() 返回的 symbol 值都是唯一的,从而确保每个属性的名字都是独一无二的。
    • Symbol()函数前不能使用new命令:生成的 Symbol 是一个原始类型的值,不是对象,因此同时也不可添加属性。
  • BigInt :大整数

2.引用数据类型也称合成类型的值(多个原始类型的值的合成):object

  • 狭义上的对象:object
  • 函数:function
  • 数组:Array

typeof 判断数据类型

 console.log(typeof 1);// numberconsole.log(typeof 'str');//stringconsole.log(typeof true);// booleanlet sym1 =Symbol();console.log(sym1)//symbolconsole.log(typeof undefined);//undefinedconsole.log(typeof function(){});//functionconsole.log(typeof {});//objectconsole.log(typeof []);//objectconsole.log(null);//object
  • 无法正确判断null:null二进制是4个0,typeof 判断3个0就是object了。
  • 无法正确判断Array:Array本质上是特殊的对象。

instanceof

console.log(1 instanceof number);//false
console.log('str' instanceof string);//false
console.log(true instanceof boolean);//false
console.log(sym1 instanceof Symbol);//falseconsole.log(function(){} instanceof Function);//true
console.log([] instanceof Array);//true
console.log({} instanceof Object);//true
console.log([] instanceof Object);//true
console.log(function(){} instanceof Object);//true
  • 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。
  • instanceof只能正确判断引用数据类型,而不能判断基本数据类型。
  • null,underfined不能instanceof。
  • 主要作用就是判断Object.prototype.toString实现不了的情况。

constructor

console.log((1).constructor === Number); // true
console.log(('str').constructor === String); // true
console.log((true).constructor === Boolean); // trueconsole.log(([]).constructor === Array); // true
console.log((function() {}).constructor === Function); // true
console.log(({}).constructor === Object); // true
  • null、 undefined没有constructor,还有Symbol.constructor是Function。
  • string、number、boolean,js引擎在运行时,将其转化为object内置对象。
  • constructor在重写prototype时,constructor会丢失。

object.prototype.toString().call()

Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call('abc') ;   // [object String]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]Object.prototype.toString.call(function(){}) ; // [object Function]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call({}) ; // [object Object]Object.prototype.toString.call([]).slice(8,-1);//Array
  • 本质是:用Object原型上的toString方法作用在传入的参数的上下文中(call将this 指向传入的参数)
  • toString是Object的原型方法,默认返回当前对象的[[Class]]
    • [[Class]] : 一个字符串值,表明了该对象的类型.
  • 检测方式相对来说又比较安全稳定,不容易被修改。除非去覆盖Object.prototype.toSring方法
  • 不用toString(),是因为 Array、function等为object的实例对象 重写了toString()方法,所以调用的是重写后的toString(),而不是Object上原型toString()。
  • 无法区分自定义对象类型:Symbol.toStringTag属性 可以定制[[Class]] 属性,也就是[object type] 中的type。