js类型判断的方法(JS的基本类型共有三种)

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《js类型判断的方法(JS的基本类型共有三种)》的相关信息,《js类型判断的方法(JS的基本类型共有三种)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《js类型判断的方法(JS的基本类型共有三种)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

今天分享3种JavaScript类型判断的方法:typeof、instanceof、constructor。


首先先看下所有的数据类型:

  • 空值(null)
  • 未定义(undefined)
  • 布尔值(boolean)
  • 数字(number)
  • 字符串(string)
  • 对象 (object)
  • 符号(symbol, ES6中新增)
  • 大整数(BigInt, ES2020 引入)

除去object,其他的我们统称基本类型,最后两个类型为新引入的前端数据类型。

Symbol: 是ES6中引入的一种原始数据类型,表示独一无二的值。

BigInt:是 ES2020 引入的一种新的数据类型,用来解决 JavaScript中数字只能到 53 个二进制位(JavaScript 所有数字都保存成 64 位浮点数,大于这个范围的整数,无法精确表示的问题。具体可查看:新数据类型 — BigInt


1.typeof

example:

console.log(typeof ""); // stringconsole.log(typeof 1 ); // numberconsole.log(typeof NaN ); // numberconsole.log(typeof true); // booleanconsole.log(typeof undefined); // undefinedconsole.log(typeof function(){}); // functionconsole.log(typeof isNaN); // functionconsole.log(typeof Symbol()); // symbolconsole.log(typeof 123n); // bigintconsole.log(typeof []); // objectconsole.log(typeof {}); // objectconsole.log(typeof null); // objectconsole.log(typeof new Date()); // objectconsole.log(typeof new RegExp()); // object

对于数组,对象,null以及时间等数据,typeof只能返回object,而不能直接返回对应的类型,还需要通过其他法判断。

2.instanceof

example:

console.log(12 instanceof Number); // falseconsole.log('22' instanceof String); // falseconsole.log(true instanceof Boolean); // falseconsole.log(null instanceof Object); // falseconsole.log(undefined instanceof Object); // falseconsole.log(function a() {} instanceof Function); // trueconsole.log([] instanceof Array); // trueconsole.log({a: 1} instanceof Object); // trueconsole.log(new Date() instanceof Date); // true

简单来说就是,判断某个数据是否是由某个构造函数的实例,如果是,返回true,不是就返回false。

深层次来讲就是,instanceof 右边的prototype是否能在instanceof左侧的数据的_proto_原型链上找到,这是个遍历的过程。找到就是true。

3.constructor

example:

console.log('22'.constructor === String) // trueconsole.log(true.constructor === Boolean) // trueconsole.log([].constructor === Array) // trueconsole.log(document.constructor === HTMLDocument) // trueconsole.log(window.constructor === Window) // trueconsole.log(new Number(22).constructor === Number) // trueconsole.log(new Function().constructor === Function) // trueconsole.log(new Date().constructor === Date) // trueconsole.log(new RegExp().constructor === RegExp) // trueconsole.log(new Error().constructor === Error) // true

constructor是追溯对象的出生地,也就是说可以知道某个对象是由哪个构造函数产生的。

原理其实是当构造函数被创建时,会在它的prototype上创建constructor属性,而该属性又指向函数本身,当实例被创建时,它的constructor会被继承,嗯….构造函数就是实例的类型。

注意:null 和 undefined 是没有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。

结尾:其实还有一种方法:
Object.prototype.toString.call(),感兴趣的自己去查文档研究研究。

笨笨网美国主机,w ww.2 b p .n e t
提醒:《js类型判断的方法(JS的基本类型共有三种)》最后刷新时间 2025-03-21 11:17:29,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《js类型判断的方法(JS的基本类型共有三种)》该内容的真实性请自行鉴别。