基本类型
类型检测
- typeof
- typeof 用于返回以下原始类型
- 基本类型:number/string/boolean
- function
- object
- undefined
- instanceof
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
也可以理解为是否为某个对象的实例,typeof不能区分数组,但instanceof则可以。
- 值类型与对象
下面是使用字面量与对象方法创建字符串,返回的是不同类型。
let hd = "mkimq"
let cms = new String("mkimq.com")
console.log(typeof hd, typeof cms) // string object
只有对象才有方法使用,但在JS中也可以使用值类型调用方法,因为它会在执行时将值类型转为对象。
let hd = "mkimq"
let cms = new String("mkimq.com")
console.log(hd.length) // 9
console.log(cms.length) // 5
String
字符串类型是使用非常多的数据类型,也是相对简单的数据类型。
- 转义符号
有些字符有双层含义,需要使用 \ 转义符号进行含义转换。下例中引号为字符串边界符,如果输出引号时需要使用转义符号。
常用转义符号列表如下
符号 | 说明 |
---|---|
\t | 制表符 |
\n | 换行 |
\\ | 斜杠符号 |
\' | 单引号 |
\" | 双引号 |
- 连接运算符
- 使用 + 可以连接多个内容组合成字符串,经常用于组合输出内容使用。
- 使用 += 在字符串上追回字符内容
- 模板
const str = 'Hello World!'
console.log(`${str}`)
- 获取长度
使用length属性可以获取字符串长度
- 大小写转换
// MKIMQ.COM
console.log('mkimq.com'.toUpperCase())
// mkimq.com
console.log('MKIMQ.COM'.toUpperCase())
- 移除空白
- 使用trim删除字符串左右的空白字符
- 使用trimLeft删除左边空白,使用trimRight删除右边空白
- 获取单字符
从0开始的位置获取字符
console.log('mkimq'.charAt(3))
console.log('mkimq'[3])
- 截取字符串
- 使用 slice、substr、substring 函数都可以截取字符串。
- slice、substring 第二个参数为截取的结束位置
- substr 第二个参数指定获取字符数量
- 查找字符串
console.log('mkimq.com'.indexOf('m')) // 0
console.log('mkimq.com'.indexOf('m', 3)) // 3 从第3个字符向后搜索
console.log('mkimq.com'.lastIndexOf('m')) // 3
console.log('mkimq.com'.lastIndexOf('m', 3)) // 0 从第3个字符向前搜索
// search() 方法用于检索字符串中指定的子字符串,也可以使用正则表达式搜索
const str = 'mkimq.com'
console.log(str.search('com')) // 6
console.log(str.search(/\.com/i)) // 5
// includes 字符串中是否包含指定的值,第二个参数指查找开始位置
console.log('mkimq.com'.includes('o')) // true
console.log('mkimq.com'.includes('h', 11)) // false
// startsWith 是否是指定位置开始,第二个参数为查找的开始位置。
console.log('mkimq.com'.startsWith('m')) // true
console.log('mkimq.com'.startsWith('k', 1)) // true
// endsWith 是否是指定位置结束,第二个参数为查找的结束位置。
console.log('mkimq.com'.endsWith('m')) // true
console.log('mkimq.com'.endsWith('k', 2)) // true
- 替换字符串
replace 方法用于字符串的替换操作
- 重复生成
'*'.repeat(3)
- 类型转换
// 分隔字母 将字符串转换为数组
const name = 'mkimq'
name.split('') // 参数分割字符
// 隐式类型转换会根据类型自动转换类型
const str = 99 + ''
// 使用 String 构造函数可以显示转换字符串类型
const str = String(99)
// js中大部分类型都是对象,可以使用类方法 toString转化为字符串
const num = 99
num.toString()
Boolean
布尔类型包括 true 与 false 两个值,开发中使用较多的数据类型。
- 声明定义
new Boolean(true)
new Boolean(false)
// 字面量创建布尔类型 推荐
const b = true
- 隐式转换
数据类型 | true | false |
---|---|---|
String | 非空字符串 | 空字符串 |
Number | 非0的数值 | 0 、NaN |
Array | 数组不参与比较时 | 参与比较的空数组 |
Object | 所有对象 | |
undefined | 无 | undefined |
null | 无 | null |
NaN | 无 | NaN |
当与boolean类型比较时,会将两边类型统一为数字1或0。 如果使用Boolean与数值比较时,会进行隐式类型转换 true转为1,false 转为0。
- 显式转换
使用 !! 转换布尔类型
使用 Boolean 函数可以显式转换为布尔类型
Number
- 声明定义
const num = new Number(1)
const num2 = 2
- 基本函数
// 判断是否为整数
Number.isInteger(1.2)
// 指定返回的小数位数可以四舍五入
(16.556).toFixed(2)
- NaN
表示无效的数值,下例计算将产生NaN结果。
Number('mkimq') // NaN
2 / 'mkimq' // NaN
NaN不能使用 == 比较,使用Number.isNaN(1)
Object.is 方法判断两个值是否完全相同 Object.is(1, NaN)
- 类型转换
- Number
- 使用Number函数基本上可以转换所有类型
- parseInt
- 提取字符串开始去除空白后的数字转为整数。
- parseFloat
- 转换字符串为浮点数,忽略字符串前面空白字符。
使用乘法进行隐式类型转换。'1' * 1
- 浮点精度
大部分编程语言在浮点数计算时都会有精度误差问题
- 处理方式
- 一种方式使用toFixed 方法进行小数截取
- 将小数转为整数进行计算后,再转为小数也可以解决精度问题
Number.prototype.add = function (num) {
//取两个数值中小数位最大的
let n1 = this.toString().split('.')[1].length
let n2 = num.toString().split('.')[1].length
//得到10的N次幂
let m = Math.pow(10, Math.max(n1, n2))
return (this * m + num * m) / m
}
- 推荐做法
引入第三方计算库,例如:mathjs、decimal.js等。
Math
Math 对象提供了众多方法用来进行数学计算,下面我们介绍常用的方法
- 取极限值
// 使用 min 与 max 可以取得最小与最大值。
console.log(Math.min(1, 2, 3))
console.log(Math.max(1, 2, 3))
// 使用apply 来从数组中取值
console.log(Math.max.apply(Math, [1, 2, 3]))
- 舍入处理
// 取最接近的向上整数
console.log(Math.ceil(1.111)) // 2
// 得到最接近的向下整数
console.log(Math.floor(1.555)) // 1
// 四舍五入处理
console.log(Math.round(1.5)) // 2
- random
random 方法用于返回 >=0 且 <1 的随机数(包括0但不包括1)。
// 返回0~5的随机数,不包括5
Math.floor(Math.random() * 5)
// 返回0~5的随机数,包括5
Math.floor(Math.random() * (5+1))
// 取2~5的随机数(不包括5)公式为:min+Math.floor(Math.random()*(Max-min))
// 取2~5的随机数(包括5)公式为:min+Math.floor(Math.random()*(Max-min+1))
Date
网站中处理日期时间是很常用的功能,通过 Date 类型提供的丰富功能可以非常方便的操作。
- 声明日期
// 获取当前日期时间
const now = new Date()
console.log(now)
console.log(typeof date) // object
console.log(now * 1) // 获取时间戳
//直接使用函数获取当前时间
console.log(Date())
console.log(typeof Date()) // string
//获取当前时间戳单位毫秒
console.log(Date.now())
// 计算脚本执行时间
const start = Date.now()
for (let i = 0; i < 2000000; i++) {}
const end = Date.now()
console.log(end - start)
console.time("testFor")
for (let i = 0; i < 2000000; i++) {}
console.timeEnd("testFor")
// 根据指定的日期与时间定义日期对象
let now = new Date('2028-02-22 03:25:02')
console.log(now)
now = new Date(2028, 4, 5, 1, 22, 16)
console.log(now)
// 使用展示运算符处理更方便
let info = [2020, 2, 20, 10, 15, 32]
let date = new Date(...info)
console.dir(date)
- 类型转换
// 将日期转为数值类型就是转为时间戳单位是毫秒
const date = new Date('2020-2-22 10:33:12')
console.log(date * 1)
console.log(Number(date))
console.log(date.valueOf())
console.log(date.getTime())
- 对象方法
格式化输出日期
const time = new Date()
console.log(
`${time.getFullYear()}-${time.getMonth()}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`
)
封装函数用于复用
function dateFormat(date, format = 'YYYY-MM-DD HH:mm:ss') {
const config = {
YYYY: date.getFullYear(),
MM: date.getMonth() + 1,
DD: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds()
}
for (const key in config) {
format = format.replace(key, config[key])
}
return format
}
console.log(dateFormat(new Date(), 'YYYY年MM月DD日'))
系统提供的日期时间方法,更多方法请查看MDN官网
方法 | 描述 |
---|---|
Date() | 返回当日的日期和时间。 |
getDate() | 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 |
getDay() | 从 Date 对象返回一周中的某一天 (0 ~ 6)。 |
getMonth() | 从 Date 对象返回月份 (0 ~ 11)。 |
getFullYear() | 从 Date 对象以四位数字返回年份。 |
getYear() | 请使用 getFullYear() 方法代替。 |
getHours() | 返回 Date 对象的小时 (0 ~ 23)。 |
getMinutes() | 返回 Date 对象的分钟 (0 ~ 59)。 |
getSeconds() | 返回 Date 对象的秒数 (0 ~ 59)。 |
getMilliseconds() | 返回 Date 对象的毫秒(0 ~ 999)。 |
getTime() | 返回 1970 年 1 月 1 日至今的毫秒数。 |
getTimezoneOffset() | 返回本地时间与格林威治标准时间 (GMT) 的分钟差。 |
getUTCDate() | 根据世界时从 Date 对象返回月中的一天 (1 ~ 31)。 |
getUTCDay() | 根据世界时从 Date 对象返回周中的一天 (0 ~ 6)。 |
getUTCMonth() | 根据世界时从 Date 对象返回月份 (0 ~ 11)。 |
getUTCFullYear() | 根据世界时从 Date 对象返回四位数的年份。 |
getUTCHours() | 根据世界时返回 Date 对象的小时 (0 ~ 23)。 |
getUTCMinutes() | 根据世界时返回 Date 对象的分钟 (0 ~ 59)。 |
getUTCSeconds() | 根据世界时返回 Date 对象的秒钟 (0 ~ 59)。 |
getUTCMilliseconds() | 根据世界时返回 Date 对象的毫秒(0 ~ 999)。 |
parse() | 返回1970年1月1日午夜到指定日期(字符串)的毫秒数。 |
setDate() | 设置 Date 对象中月的某一天 (1 ~ 31)。 |
setMonth() | 设置 Date 对象中月份 (0 ~ 11)。 |
setFullYear() | 设置 Date 对象中的年份(四位数字)。 |
setYear() | 请使用 setFullYear() 方法代替。 |
setHours() | 设置 Date 对象中的小时 (0 ~ 23)。 |
setMinutes() | 设置 Date 对象中的分钟 (0 ~ 59)。 |
setSeconds() | 设置 Date 对象中的秒钟 (0 ~ 59)。 |
setMilliseconds() | 设置 Date 对象中的毫秒 (0 ~ 999)。 |
setTime() | 以毫秒设置 Date 对象。 |
setUTCDate() | 根据世界时设置 Date 对象中月份的一天 (1 ~ 31)。 |
setUTCMonth() | 根据世界时设置 Date 对象中的月份 (0 ~ 11)。 |
setUTCFullYear() | 根据世界时设置 Date 对象中的年份(四位数字)。 |
setUTCHours() | 根据世界时设置 Date 对象中的小时 (0 ~ 23)。 |
setUTCMinutes() | 根据世界时设置 Date 对象中的分钟 (0 ~ 59)。 |
setUTCSeconds() | 根据世界时设置 Date 对象中的秒钟 (0 ~ 59)。 |
setUTCMilliseconds() | 根据世界时设置 Date 对象中的毫秒 (0 ~ 999)。 |
toSource() | 返回该对象的源代码。 |
toString() | 把 Date 对象转换为字符串。 |
toTimeString() | 把 Date 对象的时间部分转换为字符串。 |
toDateString() | 把 Date 对象的日期部分转换为字符串。 |
toGMTString() | 请使用 toUTCString() 方法代替。 |
toUTCString() | 根据世界时,把 Date 对象转换为字符串。 |
toLocaleString() | 根据本地时间格式,把 Date 对象转换为字符串。 |
toLocaleTimeString() | 根据本地时间格式,把 Date 对象的时间部分转换为字符串。 |
toLocaleDateString() | 根据本地时间格式,把 Date 对象的日期部分转换为字符串。 |
UTC() | 根据世界时返回 1970 年 1 月 1 日 到指定日期的毫秒数。 |
valueOf() | 返回 Date 对象的原始值。 |
Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率。