基本数据类型
number
、string
、boolean
、object
、null
、undefined
、Symbol
、BigInt
注意点
null
、array
、Set
、Map
、Date
类型均为object
,map
解决了hash
的键必须为字符串的问题。
function checkType() {
console.log(typeof null === 'object') ✅
console.log(typeof [] === 'object') ✅
console.log(typeof new Set() === 'object') ✅
console.log(typeof new Map() === 'object') ✅
console.log(typeof new Date() === 'object') ✅
}
- 如何判断一个变量为数组?
function checkIsArray() {
console.log(typeof []) ❌ // 为 'object'
console.log([] instanceof Array) ✅
console.log(Array.isArray([])) ✅ // 建议使用
console.log(Object.prototype.toString.call([]).indexOf('Array') > -1) ✅
console.log(Array.prototype.isPrototypeOf([])) ✅
console.log([].constructor.toString().indexOf('Array') > -1) ✅
}
- 判断一个变量是否为
undefined
,一定要使用typeof a === 'undefined'
,原因如下
function checkUndefined() {
// undefined = 10 ❌,会直接报错
let a;
let undefined = 'other'
console.log(a === undefined) ❌
console.log(typeof a === 'undefined') ✅
}
由于 undefined
是一个全局只读变量,并不是关键字,虽然不能直接使用 undefined = 'other'
,但是却可以使用 let undefined === 'other'
定义变量,直接使用 a === undefined
有可能会导致判断不准。
null
是关键字,故无此问题。
-
number
底层采用符点数存储,故存在精度问题3.1. 如何判断两个数字相等? 3.2. 计算金额时如何保证至多两位小数?
function checkNumber() {
console.log(0.1 + 0.2) // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3) ❌
console.log(nearlyEqual(0.1 + 0.2, 0.3)) ✅
console.log(Math.floor(0.30000000000000004 * 100) / 100) // 0.3
}
function nearlyEqual(x: number, y: number, epsilon: number = Number.EPSILON) {
if (epsilon === null || epsilon === undefined) {
return x === y
}
if (x === y) {
return true
}
if (Number.isNaN(x) || Number.isNaN(y)) {
return false
}
if (Number.isFinite(x) && Number.isFinite(y)) {
const diff = Math.abs(x - y)
const DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16
if (diff < DBL_EPSILON) {
return true
} else {
return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon
}
}
return false
}