JavaScript – 数据类型
2022/5/6 1:13:07
本文主要是介绍JavaScript – 数据类型,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
前言
写着 TypeScript 学习笔记, 顺便也写点 JS 的呗.
参考
JS数据类型分类和判断
阮一峰 – 数据类型
JS 数据类型
string
number
boolan
undefined
null
object
symbol
bigint
其中 symbol 和 bigint 是后来加进去的
另外还有一些很常见但其它它们不能说是类型. array, function, class, arrow function, NaN, Regex, Date
typeof
typeof 是用来判断类型的.
console.log('string', typeof 'string'); console.log('number', typeof 1); console.log('boolean', typeof true); console.log('undefined', typeof undefined); console.log('null', typeof null); console.log('object', typeof {}); console.log('symbol', typeof Symbol('v')); console.log('bigint', typeof (100n));
结果
只有一个奇葩, null = object. 这个是历史原因.
另一组
console.log('array', typeof []); console.log('function', typeof function() {}); console.log('arrow function', typeof (() => {})); console.log('date', typeof new Date()); console.log('reg', typeof /\d/gi); console.log('NaN', typeof NaN); console.log('class', typeof class{});
结果
我们先讲好理解的, function, arraw function 都是 function, JS 的 class 其实也是 function, 所有它们三都是 function, 没问题.
reg, date 都是 new 出来的对象, 没问题
最后只剩下 array = object, NaN (not a number) = number 比较乱水了. (背起来呗)
类型判断方式
除了用 typeof 还有一些常用的技巧
判断 null
null === null
判断 NaN
isNaN(NaN)
判断 Array
Array.isArray([])
判断 Date, Regex
(new Date()) instanceof Date
黑魔法 typeof
console.log('string', Object.prototype.toString.call('string').slice(8, -1).toLowerCase());
效果
这篇关于JavaScript – 数据类型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)