1、数据类型
基础数据类型 ( 7 种 )
| 1、String 2、Number 3、Boolean 4、null 5、undefined 6、Symbol 7、bigInit |
引用数据类型 ( Object )
| 1、Object 2、Array 3、Function 4、RegExp ... |
基础数据类型和引用类型的区别
| 1、基本数据类型是存放在栈种的简单数据段,数据大小确定、内存空间大小可分配、他们是直接按值存放的,可按值访问。 |
| |
| 2、引用数据类型其具体内容是存放在堆中的,而栈中存放的是具体内容所在内存的地址及指针。 |
| |
| 3、基本数据类型调用方法时作为参数是按 【值】 传递的;引用数据类型调用方法时作为参数是按 【引用传递】 的。 |
2、数据类型的判断
typeof + 一元表达式
| 1、对于基本类型,除 null 以外,均可以返回正确结果 |
| |
| 2、对于引用类型,除 function 都返回 Object |
| |
| 3、对于 null 返回 Object |
| |
| 4、对于 Function 返回 Function |
eg: typeOf(null) => Object
eg: typeOf(Function) => Function
instanceof
| 1、instanceof 只能用来判断两个对象是否属于实例关系,而不能判断一个对象实例具体属于哪一种类型。 |
| |
| 2、一般用于判断 Array Object RegExp |
eg: console.log(arr instanceof Array) => true
constructor
| 1、null 和 undefined 是无效的对象,因此是不会有constructor 存在的,这两种类型的数据需要通过其他方式来判断。 |
| |
| 2、函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后 原有的 constructor 引用会丢失,constructor 会默认为 Object |
| |
eg: console.log(arr.constructor === Array) => true
toString()
| 1、toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的一个内部属性 [[Class]] |
| |
| 2、对于 Object 对象,直接调用 toString() 就能返回 [Object Object]。而对于其他对象,则需要通过 call 或 apply 来调用才能返回正确的类型信息。 |
eg: Object.prototype.toString.call(null) => [object Null]
3、数据类型的转换
概念
| 1、数据类型转换分为 显示数据类型转换 和 隐式数据类型转换。 |
| |
| 2、运算符发现运算的类型与预期不符,就会自动转换类型。 |
显示的转换数据类型
| 转换为 Boolean |
| |
| 1、Boolean('caix') => true; |
| |
| 2、Boolean('') => false; |
| |
| 转换为 Number |
| |
| 2、Number('123') => 123; |
| |
| 3、number('123caix') => NaN; |
| |
| 4、parseInt('123blue') => 1234; |
| |
| 5、parseInt('22.5') => 22; |
| |
| 6、parseIntFloat('22.5.55') => 22.5; |
| |
| ......... |
| |
| 转换为字符串 |
| |
| 1、String(3 > 4) => false 强转函数 |
| |
| 2、toString() |
隐式的数据转换
| 1、递增和递减操作符 => String |
| |
| 2、一元加和减操作符 => String |
| |
| 3、逻辑非 与 比较操作符 => 转为 Boolean |
| |
| 4、if do-while while 判断语句 => Boolean |
4、null 和 undefined 的区别
| 1、null: 表示空对象指针;作为对象原型的重点 |
| |
| 2、undefined: 变量申明但未赋值 |
| |
| a 定义了行参,没有传实参,显示为 undefined |
| |
| b 对象属性名不存在时,显示为 undefined |
| |
| 3、null 和 undefined 转换为 number 数据类型 |
| |
| null => 0 ; undefined => NaN |
| |
| 4、console.log(null == undefined) => true |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)