数据类型
大约 2 分钟Fe Basicjs
相关定义
动态:JavaScript 中的变量是没有类型的,与任何特定值类型没有任何关联,并且任何变量都可以分配(重新分配)所有类型的值
解释型:
弱类型:当操作涉及不匹配的类型是否,它将允许隐式类型转换,而不是抛出一个错误,对于 Symbol 和 BigInt,JavaScript 总是不允许某些隐式类型转换
一个有趣的事实:任何JS代码片段在执行前都要进行编译(所以实际上也是一门 编译语言 );当你了解熟悉了 JS引擎、编译器、作用域 之间的关系配合之后,便对这么语言会有新的认识
内置类型(八种)
JS 内置类型
<!-- 七种简单数据类型,一种复杂数据类型 -->
<p>undefined, null, boolean, number, string, symbol, object</p>
<p>bigint(新增的数据类型): 处理大量数据或高精度计算时非常有用</p>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
const resultArr = []
const undefinedType = typeof undefined
const nullType = typeof null // 这个其实是js的一个bug,修复后对现存的应用等影响太大,应该永远不会修复
const booleanType = typeof true
const numberType = typeof 42
const stringType = typeof '42'
const symbolType = typeof Symbol('a')
const objectType = typeof {}
const func = function () {}
const functionType = typeof func
resultArr.push({undefinedType})
resultArr.push({nullType: nullType + '- 这是一个历史bug'})
resultArr.push({booleanType})
resultArr.push({numberType})
resultArr.push({stringType})
resultArr.push({symbolType})
resultArr.push({objectType: objectType + '- 这是复杂数据类型'})
resultArr.push({functionType: functionType + '- 函数在ECMA中被认为是对象,但函数比较特殊,typeof就做了区分'})
document.querySelectorAll('li').forEach((li,index) => {
let result = resultArr[index]
let key = Object.keys(result)[0]
li.innerHTML = `${key}: ${result[key]}`
})
基本数据类型
- Null
- Undefined
- Boolean
- Number
- String
- BigInt
- Symbol
引用数据类型
- Object
- Function
- Array
- Date
Null
typeof null === 'object' // true
/**
* 如何判断null
*/
let a = null
!a && typeof null === 'object'
Undefined
Boolean
Number
BigInt
String
Symbol
ES6 引入的 Symbol 是为了解决什么样的问题或者说是能解决什么样的问题?
使得对象的属性具有唯一标识
Object
注意
注意区别JS的宿主浏览器中的对象(如BOM,DOM)与Object的区别,
它们的行为可能跟Object的行为不一致,是不受ECMA的约束的
Function
object的一个子类型,是可调用对象,内部属性[[call]],该属性使其可以被调用
函数对象的length属性是其声明的参数的个数
Array
object的一个子类型