第5章 基本引用类型
# Date
名词解释
UTC: Universal Time Coordinated,表示 1970 年 1 月 1 日 0 点至今所经过的毫秒数。
列举常用的日期实例的方法
方法 | 描述 |
---|---|
Date() | 返回当前的日期时间 |
getDate() (opens new window) | 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 |
getDay() (opens new window) | 从 Date 对象返回一周中的某一天 (0 ~ 6)。 |
getMonth() (opens new window) | 从 Date 对象返回月份 (0 ~ 11)。 |
getFullYear() (opens new window) | 从 Date 对象以四位数字返回年份。 |
getHours() (opens new window) | 返回 Date 对象的小时 (0 ~ 23)。 |
getMinutes() (opens new window) | 返回 Date 对象的分钟 (0 ~ 59)。 |
getSeconds() (opens new window) | 返回 Date 对象的秒数 (0 ~ 59)。 |
getTime() (opens new window) | 返回 1970 年 1 月 1 日至今的毫秒数,也就是时间戳。 |
setDate() (opens new window) | 设置 Date 对象中月的某一天 (1 ~ 31)。 |
此外,直接调用 Date.now(),也可以返回 1970 年 1 月 1 日至今的毫秒数。
# RegExp
正则表达式的简单语法表示如下:
let expression = /pattern/afgls
其中 pattern 是模式,即正则表达式。flags 是标记,用于控制表达式的行为,标记罗列如下:
- g:全局模式,查找字符串的全部匹配的内容
- i:不区分大小写
- m:多行模式,注意只有使用^和$模式时才会起作用
- y:粘附模式,表示只查找从 lastIndex 开始及之后的字符串
# 元字符
( ) [ ] { } \ ^ $ | ? * + .
# 实例方法
# exec()
let text = 'mon and dad and baby'
let pattern = /mon( and dad( and baby)?)?/gi
let matches = pattern.exec(text)
console.log(matches.index) // 0
console.log(matches.input) // 'mon and dad and baby'
console.log(matches[0]) // 'mon and dad and baby' 匹配整个模式的字符串
console.log(matches[1]) // ' and dad and baby' 第一个捕获组的字符串
console.log(matches[2]) // ' and baby'
2
3
4
5
6
7
8
9
再看一个例子
let text = 'cat,bat,sat,fat'
let pattern = /.at/g
let matches = pattern.exec(text)
console.log(matches.index) // 0
console.log(matches[0]) // cat
console.log(pattern.lastIndex) // 3
matches = pattern.exec(text)
console.log(matches.index) // 4
console.log(matches[0]) // bat
console.log(pattern.lastIndex) // 7
matches = pattern.exec(text)
console.log(matches.index) // 8
console.log(matches[0]) // sat
console.log(pattern.lastIndex) // 11
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
如果上述 pattern 没有 g 模式,则 index 都是 0,即只返回第一个匹配的信息
# test()
如果输入的文本与模式匹配,则返回 true,否则为 false。
let text = '000-00-0000'
let pattern = /\d{3}-\d{2}-\d{4}/
console.log(pattern.test(text))
2
3
# 构造函数属性
属性 | 说明 |
---|---|
input | 搜索的原始字符串 |
lastMatch | 匹配的文本 |
lastParen | 匹配的捕获组 |
leftContext | input 字符串中出现在 lastMatch 之前的文本 |
rightContext | input 字符串中出现在 lastMatch 之后的文本 |
let text = 'this has been a short summer'
let pattern = /(.)hort/g
if (pattern.test(text)) {
console.log(RegExp.input) // this has been a short summer
console.log(RegExp.lastMatch) // short
console.log(RegExp.lastParen) // s
console.log(RegExp.leftContext) // this has been a
console.log(RegExp.rightContext) // summer
}
2
3
4
5
6
7
8
9
RegExp 构造函数的属性不要在生产上使用,因为还没有 Web 标准
# 原始包装类型
先看一个示例
let s1 = 'some text'
let s2 = s1.slice(2)
2
s1 的类型是字符串,逻辑上说是没有方法的,但这里出现了。实际执行过程如下:
- 创建一个 String 类型的实例
- 调用实例上的特定方法
- 销毁实例
俗称装箱和拆箱。
原始包装类型和引用类型的主要区别在于对象的生命周期。
引用类型的实例在离开作用域时会被销毁;
上述过程创建的原始包装类型则只会存在于访问它的代码执行瞬间,即调用方法的时间。
看看 String 和 Number 常用的方法和属性
# String
# length
表示字符串的长度
# charAt()
返回给定索引位置的字符
# charCodeAt()
查看指定索引位置的字符编码
# fromCharCode()
根据指定的 UTF-16 码元创建字符串中的字符
注意这 2 个方法都只在基本多语言平面(BMP)有效,扩展到 Unicode 增补字符平面就不成立了,对应的替代方法是 codePointAt 和 fromCodePoint。
let message = 'abcde'
console.log(message.length) // 5
console.log(message.charAt(2)) // c
console.log(message.charCodeAt(2)) // 99
console.log(String.fromCharCode(97, 98, 99)) // abc
2
3
4
5
# concat()
将字符串进行拼接,一般我们使用 “+”来拼接,或者直接在模板字符串(es6)直接书写
# slice()
用于提取子字符串。第一个参数表示子字符串开始的位置,第二个参数表示子字符串结束的位置,省略第二个参数则默认提取到字符串末尾。
如果参数是负数,则直接加上字符串长度即可。
类似的有 substr,substring,不过一般使用 slice 足矣。
let str = 'hello world'
console.log(str.slice(3)) // lo world
console.log(str.slice(3, 7)) // lo w
console.log(str.slice(3, 2)) //
console.log(str.slice(-3)) // rld
2
3
4
5
# indexOf()和 lastIndexOf()
分别表示从左往右和从右往左查找传入的字符串,有则返回索引,无则返回-1.
第二个参数表示搜索开始的位置。
let str = 'hello world'
console.log(str.indexOf('o')) // 4
console.log(str.lastIndexOf('o')) // 7
console.log(str.indexOf('o', 6)) // 7
console.log(str.lastIndexOf('o', 4)) // 4
2
3
4
5
# startsWith()、endsWith()和 includes()
startsWith:传入字符串是否位于原字符串的开头。
endsWith:传入字符串是否位于原字符串的末尾。
includes:原字符串是否包含了传入字符。
let message = 'foobarbaz'
console.log(message.startsWith('foo')) // true
console.log(message.startsWith('bar')) // false
console.log(message.endsWith('baz')) // true
console.log(message.endsWith('bar')) // false
console.log(message.includes('bar')) // true
console.log(message.includes('abc')) // false
2
3
4
5
6
7
startsWidth 和 includes 可接受第二个参数,表示开始搜索的索引。而 endsWith 第二个参数表示需要匹配的字符串末尾的位置。
let message = 'foobarbaz'
console.log(message.startsWith('foo')) // true
console.log(message.startsWith('foo', 1)) // false
console.log(message.includes('bar')) // true
console.log(message.includes('bar', 4)) // false
console.log(message.endsWith('baz')) // true
console.log(message.endsWith('baz', message.length - 1)) // false
2
3
4
5
6
7
# trim()
创建字符串的一个副本,删除前后所有空格符。
let str = ' hello world '
let res = str.trim()
console.log(str) // ' hello world '
console.log(res) // 'hello world'
2
3
4
# 字符串的迭代和解构
可以将字符串理解为一个数组,可以使用for...of
进行遍历,也可以使用...
扩展运算符。
let message = 'abcd'
for (let item of message) {
console.log(item) // a b c d
}
console.log([...message]) // [ 'a', 'b', 'c', 'd' ]
2
3
4
5
# toLowerCase()和 toLocaleLowerCase()
两个方法都是将字符串全部转为小写,区别在于特定地区使用 toLocaleLowerCase 才能正确转换。
同理,toUpperCase 和 toLocaleUpperCase()可以将字符串转为大写。
# 模式匹配方法 match,search,replace,split
match本质就是正则对象的 exec 方法,返回数组(包含捕获组)。
search,用法跟 indexOf 类似,参数是正则表达式。
replace,接收 2 个参数,第一个参数是 RegExp 对象或字符串,第二个参数是字符串或函数。
如果第一个参数是正则,一般要带上全局标记 g,不然只会替换第一个匹配的字符串。
如果第二个参数是字符串,有几个特殊字符序列,用于特殊含义。
字符序列 | 替换文本 |
---|---|
$& | 相当于 RegExp.lastMatch |
$' | 相当于 RegExp.rightContext |
$` | 相当于 RegExp.leftContext |
$n | 匹配第 n 个捕获组的字符串,n=0~9 |
let str = 'abc111abc222'
let res1 = str.replace(/abc/g, '$&') // abc111abc222
let res2 = str.replace(/abc/g, "$'") // 111abc222111222222
let res3 = str.replace(/abc/g, '$`') // 111abc111222
let res4 = str.replace(/(abc)(222)/g, '$1-$2') // abc111abc-222
2
3
4
5
此外,如果第二个参数是函数,则有 3 个形参
match 表示与模式匹配的字符串
pos 表示匹配的位置
originText 表示原字符串
let str = 'a1'
let res = str.replace(/[a1]/g, (match, pos, originText) => {
// a 0 a1
// 1 1 a1
console.log(match, pos, originText)
if (match === 'a') {
return 'A'
} else if (match === '1') {
return '2'
}
})
console.log(res) // A2
2
3
4
5
6
7
8
9
10
11
12
split,将字符串拆分到数组
let str = 'a,b,c'
console.log(str.split(',')) // [ 'a', 'b', 'c' ]
2
# Number
# toFixed
返回包含指定小数点位数的数值字符串,如果位数不够会补 0,如果超出,则四舍五入取值。
let num1 = 10
console.log(num1.toFixed(2)) // 10.00
let num2 = 10.005
console.log(num2.toFixed(2)) // 10.01
2
3
4
# Number.isInteger()
判断一个数组是否为整数。
console.log(Number.isInteger(1)) // true
console.log(Number.isInteger(1.0)) // true
console.log(Number.isInteger(1.1)) // false
2
3
# 单例内置对象
# Global
全局对象存在于全局作用域,通常不用显示指定。全局作用域中定义的变量和函数默认是 Global 的属性。
# encodeURIComponent()和 decodeURIComponent()
分别表示对字符串进行编码和解码,常用于浏览器 url 传参,成对使用。
此外,encodeURI 和 decodeURI 不会处理全部字符,如
let str = '123abc@#$'
console.log(encodeURI(str)) // 123abc@#$
console.log(encodeURIComponent(str)) // 123abc%40%23%24
2
3
# eval()
是一个完整的 ECMAScript 解释器,参数是要执行的一段 js 字符串
eval("console.log('hi')")
等价于
console.log('hi')
此外,它相当于存在当前作用域,可以调用当前作用域的变量。
let msg = 'hello'
eval('console.log(msg)') // 'hello'
2
# Math
# min()和 max()
返回一组数值中的最小值和最大值
# ceil()、floor()和 round()
都表示取整,区别如下
ceil:向上舍入
floor:向下舍入
round:四舍五入
# random()
返回[0,1)之间的随机数。
// 返回1-10之间的随机数
Math.floor(Math.random() * 10 + 1)
2