对ES6新特性的简单总结
let和const
特点:
- 块级作用域
- 不会变量提升
const
- 声明过后不允许重新赋值
- 要求声明同时赋值
- 只是要求内层指向不允许被修改, 对于数据成员的修改是没有问题的
const obj = {}
obj.name = 'zce' // 允许
obj = {} // 报错
数组的解构
const arr = [100, 200, 300]
const [foo, bar, baz] = arr //foo=100 bar=200 baz=300
const [, , baz] = arr //baz=300
const [foo, ...rest] = arr //rest= [200, 300]
const [foo, bar, baz = 123, more = 'default value'] = arr //baz=300 more='default value'
对象的解构
const obj = { name: 'zce', age: 18 }
const { name: objName = 'jack' } = obj // objName别名,设置默认值
模板字符串
- ${} 插入表达式
- 允许换行,空格
- 通过\转义,`string`
const name = 'tom'
const msg = `this is a \`string\`,hey, ${name} --
- ${1 + 2} ---- ${Math.random()}`
输出:
this is a `string`,hey, tom --
- 3 ---- 0.9494610500142142
带标签的模板字符串
- 模板字符串的标签就是一个特殊的函数
- 使用这个标签就是调用这个函数
const name = 'tom'
const gender = false
function myTagFunc (strings, name, gender) {
console.log(strings, name, gender) // [ 'hey, ', ' is a ', '.' ] tom false
const sex = gender ? 'man' : 'woman'
return strings[0] + name + strings[1] + sex + strings[2]
}
const result = myTagFunc`hey, ${name} is a ${gender}.` // 调用
console.log(result) // hey, tom is a woman.
字符串的扩展方法
- startsWith // 以什么开头
- endsWith // 以什么结尾
- includes // 包含
函数参数
默认值
function foo (enable = true) {...} // 有传参取传参,无传参取默认值
剩余参数
function foo (first, ...rest) {
console.log(rest) // [2,3,4] 剩余参数
console.log(arguments) // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 } 伪数组
}
foo(1, 2, 3, 4)
展开运算符
const arr = ['foo', 'bar', 'baz']
console.log(...arr) // foo bar baz 相当于 console.log.apply(console, arr)
箭头函数
arr.filter(i => i % 2)
注意点:不会改变this的指向
对象字面量
const person = {
[Math.random()]: 11 // 通过 [] 让表达式的结果作为属性名,动态属性
}
Object.assign
const result = Object.assign(target, source1, source2) // 遇到重复属性,后面覆盖前面的
const funcObj = Object.assign({}, obj) // 深拷贝对象
Object.is
console.log(
+0 === -0, // => true
NaN === NaN, // => false
Object.is(+0, -0), // => false
Object.is(NaN, NaN), // => true
)