# 6.ES6 内置对象扩展
# 数组
# 扩展运算符(展开语法)
扩展运算符可以将数组或者对象转换为用逗号分隔的参数序列
let arr = [1, 2, 3]
...arr // 1, 2, 3
console.log(...arr) // 1 2 3
console.log(1, 2, 3) // 1 2 3
let color = ['red', 'green', 'blue', 'pink', 'yellow']
console.log(...color)
扩展运算符可以应用于合并数组
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = [...arr1, ...arr2]
console.log(...arr3)
// 也可以这样子使用
arr1.push(...arr2)
console.log(...adrr1)
可以将类数组转换为真正的数组
let allDivs = document.getElementsByTagName('div')
// 这里获取的是div元素集合,是一个伪数组
allDivs = [...allDivs]
// 将伪数组转换为真正的数组之后,就可以使用数组的方法
# 构造函数方法:Array.from()
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
}
// arrayLike 是一个伪数组
let arr2 = Array.from(arrayLike)
// ['a', 'b', 'c']
Array.from(arrLike, fn())
这个方法还可以传递第二个参数,用于加工伪数组
let arrayLike = {
'0': 1,
'1': 2,
'2': 3,
length: 3
}
let array = Array.form(arrayLike, item => item*2)
# 构造方法:of()
将任意的数据类型,转换成数组
console.log(Array.of(3,10,20,[1,3,4], {id: 1}))
# 构造方法:copyWithin()
console.log([1,2,3,6,8,9].copyWithin(0,3))
// 6,8,9,6,8,9
console.log([1,2,3,4,5,6].copyWithin(0,5))
// 6,2,3,4,5,6
# 实例方法:find()
用于找出第一个符合条件的数组成员,如果没有找到则返回undefined
let arr = [
{
id: 1,
name: '张三'
},
{
id: 2,
name: '李四'
}
]
let target = arr.find((item,index) => item.id === 2)
console.log(target) // { id: 2, name: '李四' }
# 实例方法:findIndex()
用于找出第一个符合条件的数组的成员的位置,如果没有找到则返回-1
let arr = [1, 3, 6, 5, 4]
let index = arr.findIndex((value, index) => value === 5)
console.log(index)
let arr2 = [1, 1, 3, 3, 5, 6, 5]
let index2 = arr2.findIndex(value => value === 5)
console.log(index2) //只输出第一个符合条件的位置
# 实例方法: includes()
表示某个数组时候包含给定的值,返回布尔值
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
# String
# 模板字符串
ES6新增的创建字符串的方式,使用反引号定义
let name = `zhangsan`
模板字符串可以解析变量
let name = `zhangsan`
let sayHello = `hello, my name is ${name}`
模板字符串中可以换行
let result = {
name: 'zhangsan',
age: 20,
sex: '男'
}
let html = `
<div>
<span>${result.name}</span>
<span>${result.age}</span>
</div>
`
模板字符串可以调用函数
const sayHello = () => '我就试试'
let html = `模板字符串 ${sayHello()}`
# 实例方法:startsWith() 和 endsWith()
- startsWith() 表示参数字符串是否在原字符串的开头,返回布尔值
- endsWith() 表示参数字符串是否在原字符串的结尾,返回布尔值
let str = 'Hello World!'
str.startsWith('Hello') // true
str.endsWith('!') // true
str.startsWith('h') // false
# 实例方法:repeat()
repeat方法表示将原字符串重复n次,返回一个新字符串
console.log('x'.repeat(10)) // xxxxxxxxxx
# Object
# is()
比较两个值是否严格相等
console.log(NaN === NaN) // false
console.log(Object.is(NaN,NaN)) // true
# assign()
浅拷贝
Object.assign(target, obj1, obj2...)
let o = Object.assign({}, {a:1}, {b:2})
console.log(o)
← 5.剩余参数 7.ES6新增数据类型 →